From afb419af04f7057e53fcbd11f14e1b1e8da2ed10 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Fri, 29 Sep 2023 03:45:17 +0100 Subject: [PATCH 01/31] CP-44767, CP-44766 & CP-44765: Refactor usage of VM restrictions and add `reference_label` to OVFs (#3211) * Tidy up `VM` extension: use `var` * Tidy up `VM` extension: remove redundant initialisers * Tidy up `VM` extension: use type keywords when possible * Tidy up `VM` extension: merge conditional expressions * Tidy up `VM` extension: remove redundant qualifiers * Tidy up `VM` extension: remove redundant type arguments * Tidy up `VM` extension: remove redundant `else`s and parentheses * Tidy up `VM` extension: fix naming * Tidy up `VM` extension: misc changes * Tidy up `VM` extension: use `null` propagation * Tidy up `VM` extension: fix whitespace * Tidy up `VM` extension: apply ReSharper Code Cleanup utility * Tidy up `VM` extension: Fix naming of private string array * CP-44767: Ignore VM restriction when fetching `MaxVCPUsAllowed` Instead, fetch the highest available value in all templates for the host. This means that VMs imported from vhd won't automatically default to `DEFAULT_NUM_VCPUS_ALLOWED`, and that VMs that have been kept across XenServer upgrades won't be limited to the number of vCPUs in their own (possibly outdated) restrictions * CP-44766: Use value in template with a matching `reference_label` when checking VM restrictions * Move restriction getters to own region * CP-44766: Use matching templates to fetch VM restrictions - Rewrite `GetRestrictions...` methods to perform simpler operations - Add `GetIntRestrictionValue` and `GetBoolRestrictionValue` wrappers to `GetRestrictionValueFromMatchingTemplate` - Now all calls to a restrictions first check the template value, with a fall-back to defaults * CP-44765: Export `reference-label` when generating OVFs --------- Signed-off-by: Danilo Del Busso --- XenAdmin/Commands/ActivateVBDCommand.cs | 4 +- XenAdmin/Commands/DeactivateVBDCommand.cs | 4 +- XenAdmin/Commands/InstallToolsCommand.cs | 6 +- XenAdmin/Commands/VMLifeCycleCommand.cs | 10 +- .../Ballooning/VMMemoryControlsBasic.cs | 24 +- .../Ballooning/VMMemoryControlsNoEdit.cs | 2 +- XenAdmin/Controls/HaNtolControl.cs | 6 +- .../Controls/NetworkingTab/NetworkList.cs | 8 +- .../Controls/XenSearch/GroupingControl.cs | 4 +- XenAdmin/Controls/XenSearch/QueryElement.cs | 4 +- .../Checks/AssertCanEvacuateCheck.cs | 4 +- XenAdmin/Dialogs/EvacuateHostDialog.cs | 6 +- XenAdmin/Dialogs/VmSnapshotDialog.cs | 8 +- XenAdmin/SettingsPanels/EditNetworkPage.cs | 2 +- XenAdmin/SettingsPanels/GpuEditPage.cs | 2 +- XenAdmin/SettingsPanels/USBEditPage.cs | 2 +- XenAdmin/SettingsPanels/VMHAEditPage.cs | 10 +- XenAdmin/TabPages/GeneralTabPage.cs | 20 +- XenAdmin/Wizards/HAWizard.cs | 12 +- .../HAWizard_Pages/AssignPriorities.cs | 38 +- XenAdmin/XenSearch/Columns.cs | 18 +- .../VirtualisationStatePropertyQueryTests.cs | 12 +- XenModel/Actions/OvfActions/Export.cs | 5 + XenModel/Actions/Pool/EnableHAAction.cs | 2 +- XenModel/Actions/VM/HAUnprotectVMAction.cs | 2 +- XenModel/Actions/VM/InstallPVToolsAction.cs | 2 +- XenModel/Actions/VM/SetHaPrioritiesAction.cs | 8 +- XenModel/Utils/Helpers.cs | 12 +- XenModel/XenAPI-Extensions/VM.cs | 1286 +++++++++-------- XenModel/XenSearch/Common.cs | 44 +- XenModel/XenSearch/Search.cs | 4 +- 31 files changed, 830 insertions(+), 741 deletions(-) diff --git a/XenAdmin/Commands/ActivateVBDCommand.cs b/XenAdmin/Commands/ActivateVBDCommand.cs index c2d571d34b..3e4b0f8758 100644 --- a/XenAdmin/Commands/ActivateVBDCommand.cs +++ b/XenAdmin/Commands/ActivateVBDCommand.cs @@ -78,7 +78,7 @@ private bool AreIODriversNeededAndMissing(VM vm) return false; } - return !vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED); + return !vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled); } private bool CanRun(VBD vbd) @@ -139,7 +139,7 @@ protected override string GetCantRunReasonCore(IXenObject item) return Messages.TOOLTIP_DEACTIVATE_SYSVDI; if (AreIODriversNeededAndMissing(vm)) - return vm.HasNewVirtualisationStates() + return vm.HasNewVirtualizationStates() ? string.Format(Messages.CANNOT_ACTIVATE_VD_VM_NEEDS_IO_DRIVERS, Helpers.GetName(vm).Ellipsise(50)) : string.Format(Messages.CANNOT_ACTIVATE_VD_VM_NEEDS_TOOLS, BrandManager.VmTools, Helpers.GetName(vm).Ellipsise(50)); diff --git a/XenAdmin/Commands/DeactivateVBDCommand.cs b/XenAdmin/Commands/DeactivateVBDCommand.cs index de0357bbe8..87dda1e84a 100644 --- a/XenAdmin/Commands/DeactivateVBDCommand.cs +++ b/XenAdmin/Commands/DeactivateVBDCommand.cs @@ -79,7 +79,7 @@ private bool AreIODriversNeededAndMissing(VM vm) return false; } - return !vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED); + return !vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled); } private bool CanRun(VBD vbd) @@ -140,7 +140,7 @@ protected override string GetCantRunReasonCore(IXenObject item) return Messages.TOOLTIP_DEACTIVATE_SYSVDI; if (AreIODriversNeededAndMissing(vm)) - return vm.HasNewVirtualisationStates() + return vm.HasNewVirtualizationStates() ? string.Format(Messages.CANNOT_DEACTIVATE_VDI_NEEDS_IO_DRIVERS, Helpers.GetName(vm).Ellipsise(50)) : string.Format(Messages.CANNOT_DEACTIVATE_VDI_NEEDS_TOOLS, BrandManager.VmTools, Helpers.GetName(vm).Ellipsise(50)); diff --git a/XenAdmin/Commands/InstallToolsCommand.cs b/XenAdmin/Commands/InstallToolsCommand.cs index 8d4eb58fd9..9579c5c9d1 100644 --- a/XenAdmin/Commands/InstallToolsCommand.cs +++ b/XenAdmin/Commands/InstallToolsCommand.cs @@ -275,10 +275,10 @@ public static bool CanRun(VM vm) if (vm == null || vm.is_a_template || vm.Locked || vm.power_state != vm_power_state.Running) return false; - var vStatus = vm.GetVirtualisationStatus(out _); + var vStatus = vm.GetVirtualizationStatus(out _); - if (vStatus.HasFlag(VM.VirtualisationStatus.UNKNOWN) || - vStatus.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED) && vStatus.HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) + if (vStatus.HasFlag(VM.VirtualizationStatus.Unknown) || + vStatus.HasFlag(VM.VirtualizationStatus.IoDriversInstalled) && vStatus.HasFlag(VM.VirtualizationStatus.ManagementInstalled)) return false; var vmHome = vm.Home(); diff --git a/XenAdmin/Commands/VMLifeCycleCommand.cs b/XenAdmin/Commands/VMLifeCycleCommand.cs index 3ae6ec21bd..736d999913 100644 --- a/XenAdmin/Commands/VMLifeCycleCommand.cs +++ b/XenAdmin/Commands/VMLifeCycleCommand.cs @@ -162,19 +162,19 @@ protected string GetCantRunNoToolsOrDriversReasonCore(IXenObject item) if (vm == null) return null; - var status = vm.GetVirtualisationStatus(out _); + var status = vm.GetVirtualizationStatus(out _); //trying to guess the reason - if (vm.HasNewVirtualisationStates()) + if (vm.HasNewVirtualizationStates()) { - if (!status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) //note: this will also be true when the enum is in Unknown state + if (!status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) //note: this will also be true when the enum is in Unknown state return Messages.VM_MISSING_IO_DRIVERS; } else { - if (status == VM.VirtualisationStatus.NOT_INSTALLED || status.HasFlag(VM.VirtualisationStatus.UNKNOWN)) + if (status == VM.VirtualizationStatus.NotInstalled || status.HasFlag(VM.VirtualizationStatus.Unknown)) return FriendlyErrorNames.VM_MISSING_PV_DRIVERS; - if (status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + if (status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) return FriendlyErrorNames.VM_OLD_PV_DRIVERS; } diff --git a/XenAdmin/Controls/Ballooning/VMMemoryControlsBasic.cs b/XenAdmin/Controls/Ballooning/VMMemoryControlsBasic.cs index 473ed90354..8126aba953 100644 --- a/XenAdmin/Controls/Ballooning/VMMemoryControlsBasic.cs +++ b/XenAdmin/Controls/Ballooning/VMMemoryControlsBasic.cs @@ -87,11 +87,11 @@ protected override void Populate() { // If all the Virtualisation Statuses are the same, report that reason. // Otherwise give a generic message. - VM.VirtualisationStatus vs0 = vm0.GetVirtualisationStatus(out _); + VM.VirtualizationStatus vs0 = vm0.GetVirtualizationStatus(out _); bool identical = true; foreach (VM vm in vms) { - if (vm.GetVirtualisationStatus(out _) != vs0) + if (vm.GetVirtualizationStatus(out _) != vs0) { identical = false; break; @@ -99,14 +99,14 @@ protected override void Populate() } if (identical) { - var status = vm0.GetVirtualisationStatus(out _); - if (status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + var status = vm0.GetVirtualizationStatus(out _); + if (status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) labelDMCUnavailable.Text = Messages.DMC_UNAVAILABLE_NOTSUPPORTED_PLURAL; - else if (!status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) - labelDMCUnavailable.Text = vm0.HasNewVirtualisationStates() + else if (!status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) + labelDMCUnavailable.Text = vm0.HasNewVirtualizationStates() ? Messages.DMC_UNAVAILABLE_NO_IO_NO_MGMNT_PLURAL : string.Format(Messages.DMC_UNAVAILABLE_NOTOOLS_PLURAL, BrandManager.VmTools); - else if (status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + else if (status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) labelDMCUnavailable.Text = string.Format(Messages.DMC_UNAVAILABLE_OLDTOOLS_PLURAL, BrandManager.VmTools); else labelDMCUnavailable.Text = Messages.DMC_UNAVAILABLE_VMS; @@ -123,15 +123,15 @@ protected override void Populate() } else { - var status = vm0.GetVirtualisationStatus(out _); + var status = vm0.GetVirtualizationStatus(out _); - if (status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if (status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) labelDMCUnavailable.Text = Messages.DMC_UNAVAILABLE_NOTSUPPORTED; - else if (!status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) - labelDMCUnavailable.Text = vm0.HasNewVirtualisationStates() + else if (!status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) + labelDMCUnavailable.Text = vm0.HasNewVirtualizationStates() ? Messages.DMC_UNAVAILABLE_NO_IO_NO_MGMNT : string.Format(Messages.DMC_UNAVAILABLE_NOTOOLS, BrandManager.VmTools); - else if (status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + else if (status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) labelDMCUnavailable.Text = string.Format(Messages.DMC_UNAVAILABLE_OLDTOOLS, BrandManager.VmTools); else labelDMCUnavailable.Text = Messages.DMC_UNAVAILABLE_VM; diff --git a/XenAdmin/Controls/Ballooning/VMMemoryControlsNoEdit.cs b/XenAdmin/Controls/Ballooning/VMMemoryControlsNoEdit.cs index 178028036d..b8d17fc6e5 100644 --- a/XenAdmin/Controls/Ballooning/VMMemoryControlsNoEdit.cs +++ b/XenAdmin/Controls/Ballooning/VMMemoryControlsNoEdit.cs @@ -93,7 +93,7 @@ protected override void OnPaint(PaintEventArgs e) editButton.Visible = vms.All(vm => vm.power_state == vm_power_state.Halted || - vm.power_state == vm_power_state.Running && !vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.UNKNOWN)); + vm.power_state == vm_power_state.Running && !vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.Unknown)); vmShinyBar.Populate(vms, false); diff --git a/XenAdmin/Controls/HaNtolControl.cs b/XenAdmin/Controls/HaNtolControl.cs index b689a38621..f32cfd967d 100644 --- a/XenAdmin/Controls/HaNtolControl.cs +++ b/XenAdmin/Controls/HaNtolControl.cs @@ -54,7 +54,7 @@ public class HaNtolControl : UserControl protected long ntolMax = -1; protected long ntol = -1; private IXenConnection connection; - private Dictionary settings; + private Dictionary settings; private readonly CollectionChangeEventHandler VM_CollectionChangedWithInvoke; @@ -111,13 +111,13 @@ public bool UpdateInProgress /// ha_compute_hypothetical_max_host_failures_to_tolerate. May not be null. /// [Browsable(false), ReadOnly(true)] - public Dictionary Settings + public Dictionary Settings { get { return settings; } set { System.Diagnostics.Trace.Assert(value != null); - settings = new Dictionary(value); + settings = new Dictionary(value); // Trigger ntol update waitingNtolUpdate.Set(); } diff --git a/XenAdmin/Controls/NetworkingTab/NetworkList.cs b/XenAdmin/Controls/NetworkingTab/NetworkList.cs index 14c0d9df6c..c78dd77ab4 100644 --- a/XenAdmin/Controls/NetworkingTab/NetworkList.cs +++ b/XenAdmin/Controls/NetworkingTab/NetworkList.cs @@ -430,7 +430,7 @@ private void UpdateEnablement() if (vm.power_state == vm_power_state.Suspended) { RemoveButtonContainer.SetToolTip(Messages.TOOLTIP_REMOVE_NETWORK_SUSPENDED); - EditButtonContainer.SetToolTip(vm.HasNewVirtualisationStates() + EditButtonContainer.SetToolTip(vm.HasNewVirtualizationStates() ? Messages.TOOLTIP_EDIT_NETWORK_IO_DRIVERS : string.Format(Messages.TOOLTIP_EDIT_NETWORK_TOOLS, BrandManager.VmTools)); toolTipContainerActivateToggle.SetToolTip(vif.currently_attached @@ -438,12 +438,12 @@ private void UpdateEnablement() } else { - if (vm.power_state == vm_power_state.Running && !vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if (vm.power_state == vm_power_state.Running && !vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) { - RemoveButtonContainer.SetToolTip(vm.HasNewVirtualisationStates() + RemoveButtonContainer.SetToolTip(vm.HasNewVirtualizationStates() ? Messages.TOOLTIP_REMOVE_NETWORK_IO_DRIVERS : string.Format(Messages.TOOLTIP_REMOVE_NETWORK_TOOLS, BrandManager.VmTools)); - EditButtonContainer.SetToolTip(vm.HasNewVirtualisationStates() + EditButtonContainer.SetToolTip(vm.HasNewVirtualizationStates() ? Messages.TOOLTIP_EDIT_NETWORK_IO_DRIVERS : string.Format(Messages.TOOLTIP_EDIT_NETWORK_TOOLS, BrandManager.VmTools)); toolTipContainerActivateToggle.SetToolTip(vif.currently_attached diff --git a/XenAdmin/Controls/XenSearch/GroupingControl.cs b/XenAdmin/Controls/XenSearch/GroupingControl.cs index 8c0380fef9..c32eb59f98 100644 --- a/XenAdmin/Controls/XenSearch/GroupingControl.cs +++ b/XenAdmin/Controls/XenSearch/GroupingControl.cs @@ -71,14 +71,14 @@ static GroupingControl() potentialGroups.Add(hostGroup); potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.os_name)); potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.power_state)); - potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.virtualisation_status)); + potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.virtualisation_status)); potentialGroups.Add(new PropertyGroupingType(ObjectTypes.AllExcFolders, PropertyNames.type)); potentialGroups.Add(new XenModelObjectPropertyGroupingType(ObjectTypes.VM, PropertyNames.networks, poolGroup)); XenModelObjectPropertyGroupingType srGroup = new XenModelObjectPropertyGroupingType(ObjectTypes.VM | ObjectTypes.VDI, PropertyNames.storage, poolGroup); potentialGroups.Add(srGroup); potentialGroups.Add(new XenModelObjectPropertyGroupingType(ObjectTypes.VM, PropertyNames.disks, srGroup)); - potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.ha_restart_priority)); + potentialGroups.Add(new PropertyGroupingType(ObjectTypes.VM, PropertyNames.ha_restart_priority)); potentialGroups.Add(new BoolGroupingType(ObjectTypes.VM, PropertyNames.read_caching_enabled)); potentialGroups.Add(new BoolGroupingType(ObjectTypes.VM, PropertyNames.vendor_device_state)); potentialGroups.Add(applianceGroup); diff --git a/XenAdmin/Controls/XenSearch/QueryElement.cs b/XenAdmin/Controls/XenSearch/QueryElement.cs index 3dc2ff3349..570cffc788 100644 --- a/XenAdmin/Controls/XenSearch/QueryElement.cs +++ b/XenAdmin/Controls/XenSearch/QueryElement.cs @@ -74,9 +74,9 @@ static QueryElement() queryTypes.Add(new IPAddressQueryType(3, ObjectTypes.VM | ObjectTypes.Server | ObjectTypes.LocalSR | ObjectTypes.RemoteSR, PropertyNames.ip_address)); queryTypes.Add(new DatePropertyQueryType(3, ObjectTypes.VM, PropertyNames.start_time)); queryTypes.Add(new EnumPropertyQueryType(3, ObjectTypes.VM, PropertyNames.power_state)); - queryTypes.Add(new EnumPropertyQueryType(3, ObjectTypes.VM, PropertyNames.virtualisation_status)); + queryTypes.Add(new EnumPropertyQueryType(3, ObjectTypes.VM, PropertyNames.virtualisation_status)); queryTypes.Add(new ValuePropertyQueryType(3, ObjectTypes.VM, PropertyNames.os_name)); - queryTypes.Add(new EnumPropertyQueryType(3, ObjectTypes.VM, PropertyNames.ha_restart_priority)); + queryTypes.Add(new EnumPropertyQueryType(3, ObjectTypes.VM, PropertyNames.ha_restart_priority)); queryTypes.Add(new BooleanQueryType(3, ObjectTypes.VM, PropertyNames.read_caching_enabled)); queryTypes.Add(new BooleanQueryType(3, ObjectTypes.VM, PropertyNames.vendor_device_state)); queryTypes.Add(new EnumPropertyQueryType(3, /*ObjectTypes.LocalSR | ObjectTypes.RemoteSR*/ ObjectTypes.None, PropertyNames.sr_type)); diff --git a/XenAdmin/Diagnostics/Checks/AssertCanEvacuateCheck.cs b/XenAdmin/Diagnostics/Checks/AssertCanEvacuateCheck.cs index d7037f0178..c277408e52 100644 --- a/XenAdmin/Diagnostics/Checks/AssertCanEvacuateCheck.cs +++ b/XenAdmin/Diagnostics/Checks/AssertCanEvacuateCheck.cs @@ -235,7 +235,7 @@ private Problem GetProblem(IXenConnection connection, XenRef vmRef, string[] private static CannotMigrateVM.CannotMigrateVMReason GetMoreSpecificReasonForCannotMigrateVm(VM vm, CannotMigrateVM.CannotMigrateVMReason reason) { var gm = vm.Connection.Resolve(vm.guest_metrics); - var status = vm.GetVirtualisationStatus(out _); + var status = vm.GetVirtualizationStatus(out _); if (vm.IsWindows()) { @@ -244,7 +244,7 @@ private static CannotMigrateVM.CannotMigrateVMReason GetMoreSpecificReasonForCan reason = CannotMigrateVM.CannotMigrateVMReason.CannotMigrateVmNoTools; } } - else if (status == VM.VirtualisationStatus.NOT_INSTALLED || status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + else if (status == VM.VirtualizationStatus.NotInstalled || status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) { reason = CannotMigrateVM.CannotMigrateVMReason.CannotMigrateVmNoTools; } diff --git a/XenAdmin/Dialogs/EvacuateHostDialog.cs b/XenAdmin/Dialogs/EvacuateHostDialog.cs index ef111775a9..6880999c1f 100644 --- a/XenAdmin/Dialogs/EvacuateHostDialog.cs +++ b/XenAdmin/Dialogs/EvacuateHostDialog.cs @@ -831,7 +831,7 @@ public void SetError(string message, Solution solution) break; case Solution.InstallPVDrivers: - error = vm.HasNewVirtualisationStates() + error = vm.HasNewVirtualizationStates() ? string.Format(Messages.EVACUATE_HOST_INSTALL_MGMNT_PROMPT, message) : string.Format(Messages.EVACUATE_HOST_INSTALL_TOOLS_PROMPT, message, BrandManager.VmTools); break; @@ -839,8 +839,8 @@ public void SetError(string message, Solution solution) case Solution.InstallPVDriversNoSolution: // if the state is not unknown we have metrics and can show a detailed message. // Otherwise go with the server and just say they aren't installed - error = !vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.UNKNOWN) - ? vm.GetVirtualisationWarningMessages() + error = !vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.Unknown) + ? vm.GetVirtualizationWarningMessages() : string.Format(Messages.PV_DRIVERS_NOT_INSTALLED, BrandManager.VmTools); break; } diff --git a/XenAdmin/Dialogs/VmSnapshotDialog.cs b/XenAdmin/Dialogs/VmSnapshotDialog.cs index be63d01c8f..adcfc0d629 100644 --- a/XenAdmin/Dialogs/VmSnapshotDialog.cs +++ b/XenAdmin/Dialogs/VmSnapshotDialog.cs @@ -138,8 +138,8 @@ private void UpdateWarnings() labelQuiesceInfo.Text = Messages.FIELD_DISABLED; else if (_VM.power_state != vm_power_state.Running) labelQuiesceInfo.Text = Messages.INFO_QUIESCE_MODE_POWER_STATE; - else if (!_VM.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) - labelQuiesceInfo.Text = _VM.HasNewVirtualisationStates() + else if (!_VM.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.ManagementInstalled)) + labelQuiesceInfo.Text = _VM.HasNewVirtualizationStates() ? Messages.INFO_QUIESCE_MODE_NO_MGMNT : string.Format(Messages.INFO_QUIESCE_MODE_NO_TOOLS, BrandManager.VmTools); else @@ -149,8 +149,8 @@ private void UpdateWarnings() labelCheckpointInfo.Text = Messages.FIELD_DISABLED; else if (_VM.power_state != vm_power_state.Running) labelCheckpointInfo.Text = Messages.INFO_DISKMEMORY_MODE_POWER_STATE; - else if (!_VM.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) - labelCheckpointInfo.Text = _VM.HasNewVirtualisationStates() + else if (!_VM.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) + labelCheckpointInfo.Text = _VM.HasNewVirtualizationStates() ? Messages.INFO_DISKMEMORY_MODE_NO_IO_DRIVERS : string.Format(Messages.INFO_DISKMEMORY_MODE_NO_TOOLS, BrandManager.VmTools); else diff --git a/XenAdmin/SettingsPanels/EditNetworkPage.cs b/XenAdmin/SettingsPanels/EditNetworkPage.cs index fba83bfc06..b1220bd54e 100644 --- a/XenAdmin/SettingsPanels/EditNetworkPage.cs +++ b/XenAdmin/SettingsPanels/EditNetworkPage.cs @@ -366,7 +366,7 @@ public void Repopulate() foreach (VIF v in network.Connection.ResolveAll(network.VIFs)) { VM vm = network.Connection.Resolve(v.VM); - if (vm.power_state != vm_power_state.Running || vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if (vm.power_state != vm_power_state.Running || vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) continue; runningVMsWithoutTools = true; diff --git a/XenAdmin/SettingsPanels/GpuEditPage.cs b/XenAdmin/SettingsPanels/GpuEditPage.cs index 9919783ec0..dfca1fbfdb 100644 --- a/XenAdmin/SettingsPanels/GpuEditPage.cs +++ b/XenAdmin/SettingsPanels/GpuEditPage.cs @@ -69,7 +69,7 @@ public List VGpus } } - public VM.HA_Restart_Priority SelectedPriority { private get; set; } + public VM.HaRestartPriority SelectedPriority { private get; set; } #region IEditPage Members diff --git a/XenAdmin/SettingsPanels/USBEditPage.cs b/XenAdmin/SettingsPanels/USBEditPage.cs index ee4c87df56..14d5641231 100755 --- a/XenAdmin/SettingsPanels/USBEditPage.cs +++ b/XenAdmin/SettingsPanels/USBEditPage.cs @@ -46,7 +46,7 @@ namespace XenAdmin.SettingsPanels public partial class USBEditPage : XenTabPage, IEditPage { private VM _vm; - public VM.HA_Restart_Priority SelectedPriority { private get; set; } + public VM.HaRestartPriority SelectedPriority { private get; set; } public USBEditPage() { diff --git a/XenAdmin/SettingsPanels/VMHAEditPage.cs b/XenAdmin/SettingsPanels/VMHAEditPage.cs index 21ebc1f7f7..3e41a0800f 100644 --- a/XenAdmin/SettingsPanels/VMHAEditPage.cs +++ b/XenAdmin/SettingsPanels/VMHAEditPage.cs @@ -51,7 +51,7 @@ public partial class VMHAEditPage : UserControl, IEditPage private VM vm; private bool vmIsAgile; - private VM.HA_Restart_Priority origRestartPriority; + private VM.HaRestartPriority origRestartPriority; private long origNtol; private long origOrder; private long origStartDelay; @@ -263,7 +263,7 @@ public void RefillPrioritiesComboBox() m_comboBoxProtectionLevel.Items.Clear(); ToggleScanningVmAgile(false); - List restartPriorities = VM.GetAvailableRestartPriorities(vm.Connection); + List restartPriorities = VM.GetAvailableRestartPriorities(vm.Connection); foreach (var restartPriority in restartPriorities) { // add "restart" priorities only is vm is agile @@ -392,7 +392,7 @@ private bool ChangesMadeInStartupOptions() return nudOrder.Value != origOrder || nudStartDelay.Value != origStartDelay; } - public VM.HA_Restart_Priority SelectedPriority { get; private set; } + public VM.HaRestartPriority SelectedPriority { get; private set; } public List VGpus { private get; set; } @@ -586,9 +586,9 @@ private void m_linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArg private class PriorityWrapper { - public readonly VM.HA_Restart_Priority Priority; + public readonly VM.HaRestartPriority Priority; - public PriorityWrapper(VM.HA_Restart_Priority priority) + public PriorityWrapper(VM.HaRestartPriority priority) { this.Priority = priority; } diff --git a/XenAdmin/TabPages/GeneralTabPage.cs b/XenAdmin/TabPages/GeneralTabPage.cs index d35dc6190f..c5ffd5d7ed 100644 --- a/XenAdmin/TabPages/GeneralTabPage.cs +++ b/XenAdmin/TabPages/GeneralTabPage.cs @@ -1646,27 +1646,27 @@ private static void GenerateVirtualisationStatusForGeneralBox(PDSection s, VM vm if (vm != null && vm.Connection != null) { //For Dundee or higher Windows VMs - if (vm.HasNewVirtualisationStates()) + if (vm.HasNewVirtualizationStates()) { - var status = vm.GetVirtualisationStatus(out var statusString); + var status = vm.GetVirtualizationStatus(out var statusString); var sb = new StringBuilder(); if (vm.power_state == vm_power_state.Running) { - if (status.HasFlag(VM.VirtualisationStatus.UNKNOWN)) + if (status.HasFlag(VM.VirtualizationStatus.Unknown)) { sb.AppendLine(statusString); } else { //Row 1 : I/O Drivers - sb.AppendLine(status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED) + sb.AppendLine(status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled) ? Messages.VIRTUALIZATION_STATE_VM_IO_OPTIMIZED : Messages.VIRTUALIZATION_STATE_VM_IO_NOT_OPTIMIZED); //Row 2: Management Agent - sb.AppendLine(status.HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED) + sb.AppendLine(status.HasFlag(VM.VirtualizationStatus.ManagementInstalled) ? Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_INSTALLED : Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_NOT_INSTALLED); } @@ -1685,12 +1685,12 @@ private static void GenerateVirtualisationStatusForGeneralBox(PDSection s, VM vm string installMessage = string.Empty; var canInstall = InstallToolsCommand.CanRun(vm); - if (canInstall && !status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if (canInstall && !status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) { installMessage = Messages.VIRTUALIZATION_STATE_VM_INSTALL_IO_DRIVERS_AND_MANAGEMENT_AGENT; } - else if (canInstall && status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED) && - !status.HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) + else if (canInstall && status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled) && + !status.HasFlag(VM.VirtualizationStatus.ManagementInstalled)) { installMessage = Messages.VIRTUALIZATION_STATE_VM_INSTALL_MANAGEMENT_AGENT; } @@ -1721,9 +1721,9 @@ void GoToHelp() //for everything else (All VMs on pre-Dundee hosts & All non-Windows VMs on any host) else if (vm.power_state == vm_power_state.Running) { - var status = vm.GetVirtualisationStatus(out var statusString); + var status = vm.GetVirtualizationStatus(out var statusString); - if (status == VM.VirtualisationStatus.NOT_INSTALLED || status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + if (status == VM.VirtualizationStatus.NotInstalled || status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) { if (InstallToolsCommand.CanRun(vm)) { diff --git a/XenAdmin/Wizards/HAWizard.cs b/XenAdmin/Wizards/HAWizard.cs index ead51f0d5c..d038ad93ec 100644 --- a/XenAdmin/Wizards/HAWizard.cs +++ b/XenAdmin/Wizards/HAWizard.cs @@ -124,21 +124,21 @@ protected override void UpdateWizardContent(XenTabPage senderPage) xenTabPageHaFinish.Ntol = xenTabPageAssignPriorities.Ntol; int alwaysRestartHighPriority = 0, alwaysRestart = 0, bestEffort = 0, doNotRestart = 0; - foreach (VM.HA_Restart_Priority priority in xenTabPageAssignPriorities.CurrentSettings.Values) + foreach (VM.HaRestartPriority priority in xenTabPageAssignPriorities.CurrentSettings.Values) { switch (priority) { - case VM.HA_Restart_Priority.AlwaysRestartHighPriority: + case VM.HaRestartPriority.AlwaysRestartHighPriority: alwaysRestartHighPriority++; break; - case VM.HA_Restart_Priority.AlwaysRestart: - case VM.HA_Restart_Priority.Restart: + case VM.HaRestartPriority.AlwaysRestart: + case VM.HaRestartPriority.Restart: alwaysRestart++; break; - case VM.HA_Restart_Priority.BestEffort: + case VM.HaRestartPriority.BestEffort: bestEffort++; break; - case VM.HA_Restart_Priority.DoNotRestart: + case VM.HaRestartPriority.DoNotRestart: doNotRestart++; break; } diff --git a/XenAdmin/Wizards/HAWizard_Pages/AssignPriorities.cs b/XenAdmin/Wizards/HAWizard_Pages/AssignPriorities.cs index 980cda95fb..3991e67b31 100755 --- a/XenAdmin/Wizards/HAWizard_Pages/AssignPriorities.cs +++ b/XenAdmin/Wizards/HAWizard_Pages/AssignPriorities.cs @@ -83,7 +83,7 @@ public override void PopulatePage() private void UpdateMenuItems() { - List restartPriorities = VM.GetAvailableRestartPriorities(connection); + List restartPriorities = VM.GetAvailableRestartPriorities(connection); //When this line: m_dropDownButtonRestartPriority.ContextMenuStrip = this.contextMenuStrip //was called in the designer a "dummy" item was added to the contextMenuStrip by the m_dropDownButtonRestartPriority, @@ -126,7 +126,7 @@ private void VM_CollectionChanged(object sender, CollectionChangeEventArgs e) /// /// The current (uncommitted) VM restart priorities. /// - public Dictionary CurrentSettings + public Dictionary CurrentSettings { get { return haNtolIndicator.Settings; } } @@ -246,7 +246,7 @@ private void PopulateVMs() // The first case is for the HA wizard when priorities are being configured for the first time, // the second is for the edit dialog, when HA is already enabled. - VM.HA_Restart_Priority? priority = firstTime ? (VM.HA_Restart_Priority?)null : vm.HARestartPriority(); + VM.HaRestartPriority? priority = firstTime ? (VM.HaRestartPriority?)null : vm.HARestartPriority(); var row = new VmWithSettingsRow(vm, priority); newRows.Add(row); } @@ -335,16 +335,16 @@ private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventA { Debug.Assert(ProtectVmsByDefault); - var priority = isNowAgile ? VM.HaHighestProtectionAvailable(connection) : VM.HA_Restart_Priority.BestEffort; + var priority = isNowAgile ? VM.HaHighestProtectionAvailable(connection) : VM.HaRestartPriority.BestEffort; row.UpdateRestartPriority(priority); haNtolIndicator.Settings = getCurrentSettings(); } else if (!isNowAgile - && row.RestartPriority != VM.HA_Restart_Priority.BestEffort - && row.RestartPriority != VM.HA_Restart_Priority.DoNotRestart) + && row.RestartPriority != VM.HaRestartPriority.BestEffort + && row.RestartPriority != VM.HaRestartPriority.DoNotRestart) { - row.UpdateRestartPriority(VM.HA_Restart_Priority.BestEffort); + row.UpdateRestartPriority(VM.HaRestartPriority.BestEffort); haNtolIndicator.Settings = getCurrentSettings(); } @@ -377,7 +377,7 @@ private void AddVmRow(VM vm) var vms = connection.Cache.VMs.Where(v => v.HaCanProtect(Properties.Settings.Default.ShowHiddenVMs)); bool firstTime = IsHaActivatedFirstTime(vms); - VM.HA_Restart_Priority? priority = firstTime ? (VM.HA_Restart_Priority?)null : vm.HARestartPriority(); + VM.HaRestartPriority? priority = firstTime ? (VM.HaRestartPriority?)null : vm.HARestartPriority(); var row = new VmWithSettingsRow(vm, priority); dataGridViewVms.Rows.Add(row); UpdateVMsAgility(new List {vm}); @@ -485,7 +485,7 @@ private void dataGridViewVms_KeyDown(object sender, KeyEventArgs e) private void priority_Click(object sender, EventArgs e) { var menuitem = (ToolStripMenuItem)sender; - VM.HA_Restart_Priority pri = (VM.HA_Restart_Priority)menuitem.Tag; + VM.HaRestartPriority pri = (VM.HaRestartPriority)menuitem.Tag; bool changesMade = false; foreach (var row in dataGridViewVms.SelectedRows.Cast()) @@ -509,16 +509,16 @@ private void priority_Click(object sender, EventArgs e) /// /// Gets the current (uncommitted) VM restart priorities. Must be called on the GUI thread. /// - private Dictionary getCurrentSettings() + private Dictionary getCurrentSettings() { Program.AssertOnEventThread(); - Dictionary result = new Dictionary(); + Dictionary result = new Dictionary(); foreach (var row in dataGridViewVms.Rows.Cast()) { // If the restart priority is null, it means we don't know if the VM is agile yet, and we have // protectVmsByDefault == true. - result[row.Vm] = row.RestartPriority ?? VM.HA_Restart_Priority.BestEffort; + result[row.Vm] = row.RestartPriority ?? VM.HaRestartPriority.BestEffort; } return result; } @@ -534,7 +534,7 @@ private void m_dropDownButtonRestartPriority_Click(object sender, EventArgs e) foreach (ToolStripMenuItem item in contextMenuStrip.Items) { - var itemRestartPriority = ((VM.HA_Restart_Priority)item.Tag); + var itemRestartPriority = ((VM.HaRestartPriority)item.Tag); item.Checked = selectedRows.Count > 0 && selectedRows.All(s => s.RestartPriority == itemRestartPriority); } } @@ -573,7 +573,7 @@ private void updateButtons() foreach (ToolStripMenuItem item in contextMenuStrip.Items) { - VM.HA_Restart_Priority itemRestartPriority = (VM.HA_Restart_Priority)item.Tag; + VM.HaRestartPriority itemRestartPriority = (VM.HaRestartPriority)item.Tag; if (selectedRows.All(r => r.RestartPriority == itemRestartPriority)) { @@ -603,7 +603,7 @@ private void updateButtons() // Now set the buttons and tooltips) foreach (ToolStripMenuItem menuItem in contextMenuStrip.Items) { - var priority = (VM.HA_Restart_Priority)menuItem.Tag; + var priority = (VM.HaRestartPriority)menuItem.Tag; if (VM.HaPriorityIsRestart(connection, priority)) { @@ -675,7 +675,7 @@ public Dictionary GetChangedStartupOptions() if (curRow.HasChanged()) result[curRow.Vm] = new VMStartupOptions(curRow.StartOrder, curRow.StartDelay, - curRow.RestartPriority ?? VM.HA_Restart_Priority.BestEffort); + curRow.RestartPriority ?? VM.HaRestartPriority.BestEffort); } return result; } @@ -737,7 +737,7 @@ private class VmWithSettingsRow : DataGridViewRow public VM Vm { get; private set; } public long StartDelay { get; private set; } public long StartOrder { get; private set; } - public VM.HA_Restart_Priority? RestartPriority { get; private set; } + public VM.HaRestartPriority? RestartPriority { get; private set; } public bool IsAgile { get; private set; } /// @@ -781,7 +781,7 @@ public string FriendlyNonAgileReason } } - public VmWithSettingsRow(VM vm, VM.HA_Restart_Priority? priority) + public VmWithSettingsRow(VM vm, VM.HaRestartPriority? priority) { cellImage = new DataGridViewImageCell {ValueType = typeof(Image)}; cellVm = new DataGridViewTextBoxCell(); @@ -817,7 +817,7 @@ public void UpdateStartOrder(long startOrder) cellStartOrder.Value = startOrder.ToString(); } - public void UpdateRestartPriority(VM.HA_Restart_Priority? restartPriority) + public void UpdateRestartPriority(VM.HaRestartPriority? restartPriority) { RestartPriority = restartPriority; cellRestartPriority.Value = Helpers.RestartPriorityI18n(restartPriority); diff --git a/XenAdmin/XenSearch/Columns.cs b/XenAdmin/XenSearch/Columns.cs index 0decea2df3..e008de2ca7 100644 --- a/XenAdmin/XenSearch/Columns.cs +++ b/XenAdmin/XenSearch/Columns.cs @@ -99,31 +99,31 @@ protected bool CheckVMTools(IXenObject o, out GridItemBase item) VM vm = o as VM; if (vm != null) { - VM.VirtualisationStatus status = vm.GetVirtualisationStatus(out _); + VM.VirtualizationStatus status = vm.GetVirtualizationStatus(out _); if (vm.power_state != vm_power_state.Running || - status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED | VM.VirtualisationStatus.MANAGEMENT_INSTALLED) || - status.HasFlag(VM.VirtualisationStatus.UNKNOWN)) + status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled | VM.VirtualizationStatus.ManagementInstalled) || + status.HasFlag(VM.VirtualizationStatus.Unknown)) return false; - if (property == PropertyNames.memoryValue && status.HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) + if (property == PropertyNames.memoryValue && status.HasFlag(VM.VirtualizationStatus.ManagementInstalled)) return false; - if ((property == PropertyNames.diskText || property == PropertyNames.networkText) && status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if ((property == PropertyNames.diskText || property == PropertyNames.networkText) && status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) return false; string warningMessage; int colSpan; - if (property == PropertyNames.memoryValue && !status.HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) + if (property == PropertyNames.memoryValue && !status.HasFlag(VM.VirtualizationStatus.ManagementInstalled)) { - if (vm.HasNewVirtualisationStates()) + if (vm.HasNewVirtualizationStates()) { warningMessage = Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_NOT_INSTALLED; colSpan = 1; } else { - warningMessage = vm.GetVirtualisationWarningMessages(); + warningMessage = vm.GetVirtualizationWarningMessages(); colSpan = 3; } @@ -160,7 +160,7 @@ protected bool CheckVMTools(IXenObject o, out GridItemBase item) } } - if (property == PropertyNames.diskText && vm.HasNewVirtualisationStates() && !status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED)) + if (property == PropertyNames.diskText && vm.HasNewVirtualizationStates() && !status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled)) { warningMessage = Messages.VIRTUALIZATION_STATE_VM_IO_NOT_OPTIMIZED; colSpan = 2; diff --git a/XenAdminTests/SearchTests/VirtualisationStatePropertyQueryTests.cs b/XenAdminTests/SearchTests/VirtualisationStatePropertyQueryTests.cs index 29c6b12a8f..5cd9880a62 100644 --- a/XenAdminTests/SearchTests/VirtualisationStatePropertyQueryTests.cs +++ b/XenAdminTests/SearchTests/VirtualisationStatePropertyQueryTests.cs @@ -222,12 +222,12 @@ public void TestFixtureSetUp() [TestCase("Fully optimized", new[] {"vm1", "vm5"})] public void TestVirtStatusIs(string filter, string[] expectedVmNames) { - var dict = PropertyAccessors.Geti18nFor(PropertyNames.virtualisation_status) as Dictionary; + var dict = PropertyAccessors.Geti18nFor(PropertyNames.virtualisation_status) as Dictionary; Assert.NotNull(dict, "Did not find i18n for VM.VirtualisationStatus"); Assert.IsTrue(dict.TryGetValue(filter, out var status), $"Did not find i18n for {filter}"); - var query = new EnumPropertyQuery(PropertyNames.virtualisation_status, status, true); + var query = new EnumPropertyQuery(PropertyNames.virtualisation_status, status, true); CheckMatch(query, expectedVmNames); } @@ -240,21 +240,21 @@ public void TestVirtStatusIs(string filter, string[] expectedVmNames) [TestCase("Fully optimized", new[] {"vm0", "vm2", "vm3", "vm4", "vm6"})] public void TestVirtStatusIsNot(string filter, string[] expectedVmNames) { - var dict = PropertyAccessors.Geti18nFor(PropertyNames.virtualisation_status) as Dictionary; + var dict = PropertyAccessors.Geti18nFor(PropertyNames.virtualisation_status) as Dictionary; Assert.NotNull(dict, "Did not find i18n for VM.VirtualisationStatus"); Assert.IsTrue(dict.TryGetValue(filter, out var status), $"Did not find i18n for {filter}"); - var query = new EnumPropertyQuery(PropertyNames.virtualisation_status, status, false); + var query = new EnumPropertyQuery(PropertyNames.virtualisation_status, status, false); CheckMatch(query, expectedVmNames); } - private void CheckMatch(EnumPropertyQuery query, string[] expectedVmNames) + private void CheckMatch(EnumPropertyQuery query, string[] expectedVmNames) { foreach (var moqVm in _allVms) { var vm = moqVm.Object; - bool? match = query.MatchProperty(vm.GetVirtualisationStatus(out _)); + bool? match = query.MatchProperty(vm.GetVirtualizationStatus(out _)); Assert.True(match.HasValue); var name = vm.Name(); diff --git a/XenModel/Actions/OvfActions/Export.cs b/XenModel/Actions/OvfActions/Export.cs index bca323a2f9..8d549c1c29 100644 --- a/XenModel/Actions/OvfActions/Export.cs +++ b/XenModel/Actions/OvfActions/Export.cs @@ -292,6 +292,11 @@ private EnvelopeType Export(string targetDir, VM vm, Action updatePercent OVF.AddOtherSystemSettingData(ovfEnv, vsId, "recommendations", vm.recommendations, hypervisorInfo); } + if (!string.IsNullOrEmpty(vm.reference_label)) + { + OVF.AddOtherSystemSettingData(ovfEnv, vsId, "reference_label", vm.reference_label, hypervisorInfo); + } + if (vm.has_vendor_device) { //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type diff --git a/XenModel/Actions/Pool/EnableHAAction.cs b/XenModel/Actions/Pool/EnableHAAction.cs index c5d370809c..375a8737d4 100644 --- a/XenModel/Actions/Pool/EnableHAAction.cs +++ b/XenModel/Actions/Pool/EnableHAAction.cs @@ -84,7 +84,7 @@ protected override void Run() foreach (VM vm in startupOptions.Keys) { log.DebugFormat("Setting HA priority on {0} to {1}", vm.Name(), startupOptions[vm].HaRestartPriority); - VM.SetHaRestartPriority(Session, vm, (VM.HA_Restart_Priority)startupOptions[vm].HaRestartPriority); + VM.SetHaRestartPriority(Session, vm, (VM.HaRestartPriority)startupOptions[vm].HaRestartPriority); log.DebugFormat("Setting start order on {0} to {1}", vm.Name(), startupOptions[vm].Order); VM.set_order(Session, vm.opaque_ref, startupOptions[vm].Order); diff --git a/XenModel/Actions/VM/HAUnprotectVMAction.cs b/XenModel/Actions/VM/HAUnprotectVMAction.cs index f03cd50803..be98d11beb 100644 --- a/XenModel/Actions/VM/HAUnprotectVMAction.cs +++ b/XenModel/Actions/VM/HAUnprotectVMAction.cs @@ -39,7 +39,7 @@ public class HAUnprotectVMAction : AsyncAction public HAUnprotectVMAction(VM vm) : base(vm.Connection, string.Format(Messages.ACTION_HA_UNPROTECT_VM_TITLE, Helpers.GetName(vm), - Helpers.RestartPriorityI18n(VM.HA_Restart_Priority.DoNotRestart)), Messages.ACTION_HA_UNPROTECT_VM_DESCRIPTION) + Helpers.RestartPriorityI18n(VM.HaRestartPriority.DoNotRestart)), Messages.ACTION_HA_UNPROTECT_VM_DESCRIPTION) { VM = vm; ApiMethodsToRoleCheck.Add("VM.set_ha_restart_priority"); diff --git a/XenModel/Actions/VM/InstallPVToolsAction.cs b/XenModel/Actions/VM/InstallPVToolsAction.cs index ad9857f587..c6ad3f0c4d 100644 --- a/XenModel/Actions/VM/InstallPVToolsAction.cs +++ b/XenModel/Actions/VM/InstallPVToolsAction.cs @@ -86,7 +86,7 @@ protected override void Run() // 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_installed() && guestMetrics.PV_drivers_up_to_date) + if (guestMetrics != null && !VM.HasNewVirtualizationStates() && guestMetrics.PV_drivers_installed() && guestMetrics.PV_drivers_up_to_date) { this.Description = string.Format(Messages.INSTALLTOOLS_EXIST, BrandManager.VmTools); return; diff --git a/XenModel/Actions/VM/SetHaPrioritiesAction.cs b/XenModel/Actions/VM/SetHaPrioritiesAction.cs index fb18a8bce0..af179117fb 100644 --- a/XenModel/Actions/VM/SetHaPrioritiesAction.cs +++ b/XenModel/Actions/VM/SetHaPrioritiesAction.cs @@ -71,12 +71,12 @@ protected override void Run() int i = 0; foreach (VM vm in settings.Keys) { - if (VM.HaPriorityIsRestart(vm.Connection, (VM.HA_Restart_Priority)settings[vm].HaRestartPriority)) + if (VM.HaPriorityIsRestart(vm.Connection, (VM.HaRestartPriority)settings[vm].HaRestartPriority)) continue; Description = string.Format(Messages.HA_SETTING_PRIORITY_ON_X, Helpers.GetName(vm)); - VM.SetHaRestartPriority(Session, vm, (VM.HA_Restart_Priority)settings[vm].HaRestartPriority); + VM.SetHaRestartPriority(Session, vm, (VM.HaRestartPriority)settings[vm].HaRestartPriority); VM.set_order(Session, vm.opaque_ref, settings[vm].Order); VM.set_start_delay(Session, vm.opaque_ref, settings[vm].StartDelay); @@ -90,12 +90,12 @@ protected override void Run() // Then move any VMs from unprotected -> protected foreach (VM vm in settings.Keys) { - if (!VM.HaPriorityIsRestart(vm.Connection, (VM.HA_Restart_Priority)settings[vm].HaRestartPriority)) + if (!VM.HaPriorityIsRestart(vm.Connection, (VM.HaRestartPriority)settings[vm].HaRestartPriority)) continue; Description = string.Format(Messages.HA_SETTING_PRIORITY_ON_X, Helpers.GetName(vm)); - VM.SetHaRestartPriority(Session, vm, (VM.HA_Restart_Priority)settings[vm].HaRestartPriority); + VM.SetHaRestartPriority(Session, vm, (VM.HaRestartPriority)settings[vm].HaRestartPriority); VM.set_order(Session, vm.opaque_ref, settings[vm].Order); VM.set_start_delay(Session, vm.opaque_ref, settings[vm].StartDelay); diff --git a/XenModel/Utils/Helpers.cs b/XenModel/Utils/Helpers.cs index 4bf7f0d3d3..f01b7efe0b 100755 --- a/XenModel/Utils/Helpers.cs +++ b/XenModel/Utils/Helpers.cs @@ -1066,7 +1066,7 @@ public static string GetNameAndObject(IXenObject XenObject) /// /// /// - public static string RestartPriorityI18n(VM.HA_Restart_Priority? priority) + public static string RestartPriorityI18n(VM.HaRestartPriority? priority) { if (priority == null) { @@ -1078,7 +1078,7 @@ public static string RestartPriorityI18n(VM.HA_Restart_Priority? priority) } } - public static string RestartPriorityDescription(VM.HA_Restart_Priority? priority) + public static string RestartPriorityDescription(VM.HaRestartPriority? priority) { if (priority == null) { @@ -1096,9 +1096,9 @@ public static string RestartPriorityDescription(VM.HA_Restart_Priority? priority /// /// Must not be null. /// - public static Dictionary GetVmHaRestartPriorities(IXenConnection connection, bool showHiddenVMs) + public static Dictionary GetVmHaRestartPriorities(IXenConnection connection, bool showHiddenVMs) { - Dictionary result = new Dictionary(); + Dictionary result = new Dictionary(); foreach (VM vm in connection.Cache.VMs) { if (vm.HaCanProtect(showHiddenVMs)) @@ -1115,12 +1115,12 @@ public static string RestartPriorityDescription(VM.HA_Restart_Priority? priority /// /// Must not be null. /// - public static Dictionary, string> GetVmHaRestartPrioritiesForApi(Dictionary settings) + public static Dictionary, string> GetVmHaRestartPrioritiesForApi(Dictionary settings) { Dictionary, string> result = new Dictionary, string>(); foreach (VM vm in settings.Keys) { - if (settings[vm] == VM.HA_Restart_Priority.BestEffort || settings[vm] == VM.HA_Restart_Priority.DoNotRestart) + if (settings[vm] == VM.HaRestartPriority.BestEffort || settings[vm] == VM.HaRestartPriority.DoNotRestart) { // The server doesn't want to know about best-effort/do not restart VMs. // (They don't influence the plan, and sending in the dictionary gives an error). diff --git a/XenModel/XenAPI-Extensions/VM.cs b/XenModel/XenAPI-Extensions/VM.cs index 9e373fa406..7915be1e72 100644 --- a/XenModel/XenAPI-Extensions/VM.cs +++ b/XenModel/XenAPI-Extensions/VM.cs @@ -30,23 +30,94 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; using System.Timers; using System.Xml; +using Newtonsoft.Json; using XenAdmin; using XenAdmin.Core; using XenAdmin.Network; -using System.Net; -using System.Text.RegularExpressions; -using Newtonsoft.Json; - namespace XenAPI { - public partial class VM : IComparable + public partial class VM { - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + /// + /// AlwaysRestartHighPriority and AlwaysRestart are replaced by Restart in Boston; we still keep them for backward + /// compatibility + /// + public enum HaRestartPriority + { + AlwaysRestartHighPriority, + AlwaysRestart, + Restart, + BestEffort, + DoNotRestart + } + + [Flags] + public enum VirtualizationStatus + { + NotInstalled = 0, + Unknown = 1, + PvDriversOutOfDate = 2, + IoDriversInstalled = 4, + ManagementInstalled = 8 + } + + public enum VmDescriptionType + { + None, + ReadOnly, + ReadWrite + } + + /// + /// Sort in the following order: + /// 1) User Templates + /// 2) Windows VMs + /// 3) Other VMs (e.g. Linux . Names in alphabetical order) + /// 4) Citrix VMs (e.g. XenApp templates) + /// 5) Misc VMs + /// 6) Regular snapshots + /// 7) Snapshots from VMPP (CA-46206) + /// Last: Hidden VMs (only visible if "Show Hidden Objects" is on: see CA-39036). + /// + public enum VmTemplateType + { + NoTemplate = 0, //it's not a template + Custom = 1, + Windows = 2, + WindowsServer = 3, + LegacyWindows = 4, + Asianux = 5, + Centos = 6, + CoreOS = 7, + Debian = 8, + Gooroom = 9, + Linx = 10, + NeoKylin = 11, + Oracle = 12, + RedHat = 13, + Rocky = 14, + SciLinux = 15, + Suse = 16, + Turbo = 17, + Ubuntu = 18, + YinheKylin = 19, + Citrix = 20, + Solaris = 21, + Misc = 22, + Snapshot = 23, + SnapshotFromVmpp = 24, + Count = 25 //bump this if values are added + } + // The following variables are only used when the corresponding variable is missing from // the recommendations field of the VM (which is inherited from the recommendations field // of the template it was created from). This should not normally happen, so we just use @@ -58,213 +129,403 @@ public partial class VM : IComparable public const long DEFAULT_MEM_ALLOWED = 1 * Util.BINARY_TERA; public const long DEFAULT_MEM_MIN_IMG_IMPORT = 256 * Util.BINARY_MEGA; public const int DEFAULT_CORES_PER_SOCKET = 1; - public const long MAX_SOCKETS = 16; // current hard limit in Xen: CA-198276 - // CP-41825: > 32 vCPUs is only supported for trusted VMs - public const long MAX_VCPUS_FOR_NON_TRUSTED_VMS = 32; - private XmlDocument xdRecommendations = null; + public const long MAX_SOCKETS = 16; // current hard limit in Xen: CA-198276 + + // CP-41825: > 32 vCPUs is only supported for trusted VMs + public const long MAX_VCPUS_FOR_NON_TRUSTED_VMS = 32; public const int MAX_ALLOWED_VTPMS = 1; - public int MaxVCPUsAllowed() - { - XmlDocument xd = GetRecommendations(); + private const string P2V_SOURCE_MACHINE = "p2v_source_machine"; + private const string P2V_IMPORT_DATE = "p2v_import_date"; - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='vcpus-max']"); - if (int.TryParse(xn?.Attributes?["max"]?.Value, out var result)) - return result; + public const string RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY = "0"; //only used for Pre-Boston pools + public const string RESTART_PRIORITY_ALWAYS_RESTART = "1"; //only used for Pre-Boston pools - return DEFAULT_NUM_VCPUS_ALLOWED; - } + /// + /// This is the new "Restart" priority in Boston, and will replace RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY and + /// RESTART_PRIORITY_ALWAYS_RESTART + /// + public const string RESTART_PRIORITY_RESTART = "restart"; - public int MinVCPUs() + public const string RESTART_PRIORITY_BEST_EFFORT = "best-effort"; + public const string RESTART_PRIORITY_DO_NOT_RESTART = ""; + + /// + /// List of distros that we treat as Linux/Non-Windows (written in the VM.guest_metrics + /// by the Linux Guest Agent after evaluating xe-linux-distribution) + /// + private static readonly string[] LinuxDistros = { - XmlDocument xd = GetRecommendations(); + "debian", "rhel", "fedora", "centos", "scientific", "oracle", "sles", + "lsb", "boot2docker", "freebsd", "ubuntu", "neokylin", "gooroom", "rocky" + }; - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='vcpus-min']"); - if (int.TryParse(xn?.Attributes?["min"]?.Value, out var result)) - return result; + private static readonly DateTime Epoch = new DateTime(1970, 1, 1); - return 1; - } + private bool _isBeingCreated; - public bool IsRunning() + private DateTime _startupTime; + + private Timer _virtualizationTimer; + + [JsonIgnore] + public bool IsBeingCreated { - return power_state == vm_power_state.Running; + get => _isBeingCreated; + set + { + _isBeingCreated = value; + NotifyPropertyChanged("IsBeingCreated"); + } } + #region Restriction Getters + /// - /// Returns true if the VM's pool has HA enabled and the VM has a saved restart priority other than DoNotRestart. - /// Does not take account of ha-always-run. + /// Returns true if + /// 1) the guest is HVM and + /// 2a) the allow-gpu-passthrough restriction is absent or + /// 2b) the allow-gpu-passthrough restriction is non-zero /// - /// - /// - /// - public bool HasSavedRestartPriority() + public bool CanHaveGpu() { - Pool pool = Helpers.GetPoolOfOne(Connection); - return pool != null && pool.ha_enabled && !String.IsNullOrEmpty(ha_restart_priority); + if (!IsHVM()) + return false; + + return GetIntRestrictionValue(this, "allow-gpu-passthrough", 1) != 0; } - /// - /// Get the given VM's home, i.e. the host under which we are going to display it. May return null, if this VM should live - /// at the pool level. For a normal VM, we look at (1) where it's running; (2) where its storage forces it to run; - /// (3) what its affinity is (its requested but not guaranteed host). - /// - public virtual Host Home() + public bool HasSriovRecommendation() { - if (is_a_snapshot) // Snapshots have the same "home" as their VM. This is necessary to make a pool-server-VM-snapshot tree (CA-76273). - { - VM from = Connection.Resolve(snapshot_of); - return (from == null ? null : from.Home()); // "from" can be null if VM has been deleted - } + return GetIntRestrictionValue(this, "allow-network-sriov", 0) != 0; + } - if (is_a_template) // Templates (apart from snapshots) don't have a "home", even if their affinity is set CA-36286 - return null; + public bool HasVendorDeviceRecommendation() + { + return GetBoolRestrictionValue(this, "has-vendor-device", false); + } - if (power_state == vm_power_state.Running) - return Connection.Resolve(resident_on); + /// + /// Returns true if + /// 1) the guest is HVM and + /// 2a) the allow-vgpu restriction is absent or + /// 2b) the allow-vgpu restriction is non-zero + /// + public bool CanHaveVGpu() + { + if (!IsHVM() || !CanHaveGpu()) + return false; - Host storage_host = GetStorageHost(false); - if (storage_host != null) - return storage_host; - Host affinityHost = Connection.Resolve(affinity); - if (affinityHost != null && affinityHost.IsLive()) - return affinityHost; + return GetIntRestrictionValue(this, "allow-vgpu", 1) != 0; + } - return null; + public long MaxMemAllowed() + { + return GetMaxRestrictionValue(this, "memory-static-max", DEFAULT_MEM_ALLOWED); } - public VBD FindVMCDROM() + public int MaxVIFsAllowed() { - if (Connection == null) - return null; + return GetMaxRestrictionValue(this, "number-of-vifs", DEFAULT_NUM_VIFS_ALLOWED); + } - List vbds = Connection.ResolveAll(VBDs).FindAll(vbd => vbd.IsCDROM()); + public int MaxVBDsAllowed() + { + return GetMaxRestrictionValue(this, "number-of-vbds", DEFAULT_NUM_VBDS_ALLOWED); + } - if (vbds.Count > 0) - { - vbds.Sort(); - return vbds[0]; - } - else - { - return null; - } + public int MaxVCPUsAllowed() + { + return GetMaxRestrictionValue(this, "vcpus-max", DEFAULT_NUM_VCPUS_ALLOWED); } - public SR FindVMCDROMSR() + public int MinVCPUs() { - VBD vbd = FindVMCDROM(); - if (vbd != null) + return GetMinRestrictionValue(this, "vcpus-min", 1); + } + + /// + /// Attempt to fetch a restriction value from a VM template with the same + /// as the input VM.
+ /// This ensures that restriction values are not limiting guest capabilities when restrictions change + /// across server upgrades.
+ /// See CP-44766 for more info. + ///
+ /// The nullable type of the value. For instance should be used for vcpus-max + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// The XML attribute corresponding to the value we need. For instance, it's "max" for vcpus-max + /// The value if found. If not found, null is returned instead + private static T? GetRestrictionValueFromMatchingTemplate(VM vm, string field, string attribute) where T : struct + { + if (!vm.is_a_template && !string.IsNullOrEmpty(vm.reference_label)) { - VDI vdi = vbd.Connection.Resolve(vbd.VDI); - if (vdi != null) + var matchingTemplate = vm.Connection.Cache.VMs + .FirstOrDefault(v => v.is_a_template && v.reference_label == vm.reference_label); + + if (matchingTemplate != null) { - return vdi.Connection.Resolve(vdi.SR); + return GetRestrictionValue(matchingTemplate, field, attribute); } } + return null; } - public override string Name() - { - const string CONTROL_DOMAIN = "Control domain on host: "; - if (name_label != null && name_label.StartsWith(CONTROL_DOMAIN)) + /// + /// Get a value from the VM's restrictions stored in its recommendations parameter. + /// + /// The type of the value. For instance should be used for vcpus-max + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// The XML attribute of the restriction element corresponding to the value we need. For instance, it's "max" for vcpus-max + /// The value if found. If not found, null is returned instead + private static T? GetRestrictionValue(VM vm, string field, string attribute) where T : struct + { + var xd = vm.GetRecommendations(); + var xn = xd?.SelectSingleNode($@"restrictions/restriction[@field='{field}']"); + var resultString = xn?.Attributes?[attribute]?.Value; + T? result = null; + try { - var hostName = name_label.Substring(CONTROL_DOMAIN.Length); - return string.Format(Messages.CONTROL_DOM_ON_HOST, hostName); + var converter = TypeDescriptor.GetConverter(typeof(T)); + if (converter.ConvertFromString(resultString) is T convertedResult) + { + result = convertedResult; + } } - return name_label; + catch (NotSupportedException) + { + // either the XML value cannot be converted + // or there is no converter + // we simply fall back to the default value + } + return result; } - public long MaxMemAllowed() + /// + /// If the a matching template can't be found, we get the value from all template restrictions, + /// falling back to a default if none is found. + /// This can be used to fetch limits for resource counts on the VM's host. + /// See CP-44767 for more information.
+ /// Try and create wrapper methods for this call such as when possible. + ///
+ /// The type of the value. For instance should be used for vcpus-max + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// The XML attribute corresponding to the value we need. For instance, it's "max" for vcpus-max + /// A list of all the non-null values present in all cached templates. This list may be empty + private static List GetRestrictionValueAcrossTemplates(IXenObject vm, string field, string attribute) where T : struct { - XmlDocument xd = GetRecommendations(); + return vm.Connection.Cache.VMs + .Where(v => v.is_a_template) + .Select(v => GetRestrictionValue(v, field, attribute)) + .Where(value => value != null) + .Cast() + .ToList(); + } - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='memory-static-max']"); - if (long.TryParse(xn?.Attributes?["max"]?.Value, out var result)) - return result; + /// + /// Get the maximum restriction value. Attempts to fetch the value using at first.
+ /// If nothing is found, it looks for the maximum value in all templates using . + ///
+ /// The type of the value. For instance should be used for vcpus-max + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// Fallback value. Defaults to this value if no valid alternatives are found. + /// The value of the matching template if found. Else the maximum non null value in all VM templates. Else, the given defaultValue + private static T GetMaxRestrictionValue(VM vm, string field, T defaultValue) where T : struct + { + var value = GetRestrictionValueFromMatchingTemplate(vm, field, "max"); + if (value != null) + return (T) value; - return DEFAULT_MEM_ALLOWED; + var templateValues = GetRestrictionValueAcrossTemplates(vm, field, "max"); + return templateValues.Count == 0 ? defaultValue : templateValues.Max(); } - public int MaxVIFsAllowed() + /// + /// Get the minimum restriction value. Attempts to fetch the value using at first.
+ /// If nothing is found, it looks for the minimum value in all templates using . + ///
+ /// The type of the value. For instance should be used for vcpus-max + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// Fallback value. Defaults to this value if no valid alternatives are found. + /// The value of the matching template if found. Else the maximum non null value in all VM templates. Else, the given defaultValue + private static T GetMinRestrictionValue(VM vm, string field, T defaultValue) where T : struct { - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@property='number-of-vifs']"); - if (int.TryParse(xn?.Attributes?["max"]?.Value, out var result)) - return result; + var value = GetRestrictionValueFromMatchingTemplate(vm, field, "min"); + if (value != null) + return (T)value; - return DEFAULT_NUM_VIFS_ALLOWED; + var templateValues = GetRestrictionValueAcrossTemplates(vm, field, "min"); + return templateValues.Count == 0 ? defaultValue : templateValues.Min(); } - public int MaxVBDsAllowed() + /// + /// Get the restriction value. Attempts to fetch the value using . + /// + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// Fallback value. Defaults to this value if no matching templates with a non-null value are found. + /// The value of the matching template if found.Else, the given defaultValue + private static int GetIntRestrictionValue(VM vm, string field, int defaultValue) { - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@property='number-of-vbds']"); - if (int.TryParse(xn?.Attributes?["max"]?.Value, out var result)) - return result; + return GetRestrictionValueFromMatchingTemplate(vm, field, "value") ?? defaultValue; + } - return DEFAULT_NUM_VBDS_ALLOWED; + /// + /// Get the restriction value. Attempts to fetch the value using . + /// + /// The VM whose restrictions we're looking for + /// The name of the field. For the max number of vCPUs it's vcpus-max + /// Fallback value. Defaults to this value if no matching templates with a non-null value are found. + /// The value of the matching template if found.Else, the given defaultValue + private static bool GetBoolRestrictionValue(VM vm, string field, bool defaultValue) + { + return GetRestrictionValueFromMatchingTemplate(vm, field, "value") ?? defaultValue; } + private XmlDocument _xdRecommendations; + + /// + /// Parse and return the content of the recommendations XML + /// + /// Parsed XML if found. null otherwise private XmlDocument GetRecommendations() { - if (xdRecommendations != null) - return xdRecommendations; + if (_xdRecommendations != null) + return _xdRecommendations; - if (string.IsNullOrEmpty(this.recommendations)) + if (string.IsNullOrEmpty(recommendations)) return null; - xdRecommendations = new XmlDocument(); + _xdRecommendations = new XmlDocument(); try { - xdRecommendations.LoadXml(this.recommendations); + _xdRecommendations.LoadXml(recommendations); } catch { - xdRecommendations = null; + _xdRecommendations = null; } - return xdRecommendations; + return _xdRecommendations; } - public Host GetStorageHost(bool ignoreCDs) + #endregion + + + public bool IsRunning() { + return power_state == vm_power_state.Running; + } - foreach (VBD TheVBD in Connection.ResolveAll(VBDs)) + /// + /// Returns true if the VM's pool has HA enabled and the VM has a saved restart priority other than DoNotRestart. + /// Does not take account of ha-always-run. + /// + public bool HasSavedRestartPriority() + { + var pool = Helpers.GetPoolOfOne(Connection); + return pool != null && pool.ha_enabled && !string.IsNullOrEmpty(ha_restart_priority); + } + + /// + /// Get the given VM's home, i.e. the host under which we are going to display it. May return null, if this VM should + /// live + /// at the pool level. For a normal VM, we look at (1) where it's running; (2) where its storage forces it to run; + /// (3) what its affinity is (its requested but not guaranteed host). + /// + public virtual Host Home() + { + if (is_a_snapshot) // Snapshots have the same "home" as their VM. This is necessary to make a pool-server-VM-snapshot tree (CA-76273). { + var from = Connection.Resolve(snapshot_of); + return from?.Home(); // "from" can be null if VM has been deleted + } - if (ignoreCDs && TheVBD.type == vbd_type.CD) - continue; - VDI TheVDI = Connection.Resolve(TheVBD.VDI); + if (is_a_template) // Templates (apart from snapshots) don't have a "home", even if their affinity is set CA-36286 + return null; + + if (power_state == vm_power_state.Running) + return Connection.Resolve(resident_on); + + var storageHost = GetStorageHost(false); + if (storageHost != null) + return storageHost; + + var affinityHost = Connection.Resolve(affinity); + if (affinityHost != null && affinityHost.IsLive()) + return affinityHost; + + return null; + } + + public VBD FindVMCDROM() + { + if (Connection == null) + return null; + + var vbds = Connection.ResolveAll(VBDs).FindAll(vbd => vbd.IsCDROM()); + + if (vbds.Count > 0) + { + vbds.Sort(); + return vbds[0]; + } + + return null; + } + + public SR FindVMCDROMSR() + { + var vbd = FindVMCDROM(); + var vdi = vbd?.Connection.Resolve(vbd.VDI); + return vdi?.Connection.Resolve(vdi.SR); + } + + public override string Name() + { + const string controlDomain = "Control domain on host: "; + if (name_label != null && name_label.StartsWith(controlDomain)) + { + var hostName = name_label.Substring(controlDomain.Length); + return string.Format(Messages.CONTROL_DOM_ON_HOST, hostName); + } + + return name_label; + } - if (TheVDI == null || !TheVDI.Show(true)) + public Host GetStorageHost(bool ignoreCDs) + { + foreach (var theVBD in Connection.ResolveAll(VBDs)) + { + if (ignoreCDs && theVBD.type == vbd_type.CD) continue; - SR TheSR = Connection.Resolve(TheVDI.SR); - if (TheSR == null) + var theVDI = Connection.Resolve(theVBD.VDI); + + if (theVDI == null || !theVDI.Show(true)) continue; - Host host = TheSR.GetStorageHost(); - if (host != null) - { - return host; - } + var theSr = Connection.Resolve(theVDI.SR); + var host = theSr?.GetStorageHost(); + if (host != null) return host; } return null; } /// - /// Default on server is CD - disk then optical + /// Default on server is CD - disk then optical /// public string GetBootOrder() { - if (this.HVM_boot_params.ContainsKey("order")) - return this.HVM_boot_params["order"].ToUpper(); + if (HVM_boot_params.ContainsKey("order")) + return HVM_boot_params["order"].ToUpper(); return "CD"; } @@ -284,13 +545,16 @@ public int GetVcpuWeight() if (VCPUs_params != null && VCPUs_params.ContainsKey("weight")) { int weight; - if (int.TryParse(VCPUs_params["weight"], out weight)) // if we cant parse it we assume its because it is too large, obviously if it isnt a number (ie a string) then we will still go to the else - return weight > 0 ? weight : 1; // because we perform a log on what is returned from this the weight must always be greater than 0 - else - return 65536; // could not parse number, assume max + if (int.TryParse(VCPUs_params["weight"], + out weight)) // if we cant parse it we assume its because it is too large, obviously if it isnt a number (ie a string) then we will still go to the else + return + weight > 0 + ? weight + : 1; // because we perform a log on what is returned from this the weight must always be greater than 0 + return 65536; // could not parse number, assume max } - else - return 256; + + return 256; } public void SetVcpuWeight(int value) @@ -310,7 +574,7 @@ public bool InternalTemplate() public string InstallRepository() { - return Get(other_config, "install-repository"); + return Get(other_config, "install-repository"); } public string InstallDistro() @@ -330,7 +594,7 @@ public bool IsHVM() public bool HasRDP() { - var metrics = Connection.Resolve(this.guest_metrics); + var metrics = Connection.Resolve(guest_metrics); if (metrics == null) return false; // feature-ts is the feature flag indicating the toolstack @@ -340,7 +604,7 @@ public bool HasRDP() public bool RDPEnabled() { - var vmMetrics = Connection.Resolve(this.guest_metrics); + var vmMetrics = Connection.Resolve(guest_metrics); if (vmMetrics == null) return false; // data/ts indicates the VM has RDP enabled @@ -349,7 +613,7 @@ public bool RDPEnabled() public bool RDPControlEnabled() { - var metrics = Connection.Resolve(this.guest_metrics); + var metrics = Connection.Resolve(guest_metrics); if (metrics == null) return false; // feature-ts2 is the feature flag indicating that data/ts is valid @@ -371,104 +635,9 @@ public bool CanUseRDP() guestMetrics.networks.Count > 0; } - /// Returns true if - /// 1) the guest is HVM and - /// 2a) the allow-gpu-passthrough restriction is absent or - /// 2b) the allow-gpu-passthrough restriction is non-zero - /// - public bool CanHaveGpu() - { - if (!IsHVM()) - return false; - - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='allow-gpu-passthrough']"); - if (int.TryParse(xn?.Attributes?["value"]?.Value, out var result)) - return result != 0; - - return true; - } - - public bool HasSriovRecommendation() - { - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='allow-network-sriov']"); - if (int.TryParse(xn?.Attributes?["value"]?.Value, out var result)) - return result != 0; - - return false; - } - - public bool HasVendorDeviceRecommendation() - { - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='has-vendor-device']"); - if (bool.TryParse(xn?.Attributes?["value"]?.Value, out var result)) - return result; - - log.Error("Error parsing has-vendor-device on the template."); - return false; - } - - /// Returns true if - /// 1) the guest is HVM and - /// 2a) the allow-vgpu restriction is absent or - /// 2b) the allow-vgpu restriction is non-zero - /// - public bool CanHaveVGpu() - { - if (!IsHVM() || !CanHaveGpu()) - return false; - - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='allow-vgpu']"); - if (int.TryParse(xn?.Attributes?["value"]?.Value, out var result)) - return result != 0; - - return true; - } - - #region Boot Mode - - public bool IsDefaultBootModeUefi() - { - var firmware = Get(HVM_boot_params, "firmware")?.Trim().ToLower(); - return firmware == "uefi"; - } - - public string GetSecureBootMode() - { - return Get(platform, "secureboot")?.Trim().ToLower(); - } - - public bool SupportsUefiBoot() - { - return GetRecommendationByField("supports-uefi") == "yes"; - } - - public bool SupportsSecureUefiBoot() - { - return GetRecommendationByField("supports-secure-boot") == "yes"; - } - - private string GetRecommendationByField(string fieldName) - { - XmlDocument xd = GetRecommendations(); - - XmlNode xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='" + fieldName + "']"); - - return xn?.Attributes?["value"]?.Value ?? string.Empty; - } - - #endregion - // AutoPowerOn is supposed to be unsupported. However, we advise customers how to // enable it (http://support.citrix.com/article/CTX133910), so XenCenter has to be - // able to recognise it, and turn it off during Rolling Pool Upgrade. + // able to recognize it, and turn it off during Rolling Pool Upgrade. public bool GetAutoPowerOn() { return BoolKey(other_config, "auto_poweron"); @@ -481,29 +650,25 @@ public void SetAutoPowerOn(bool value) public string IsOnSharedStorage() { - foreach (XenRef vbdRef in VBDs) + foreach (var vbdRef in VBDs) { - VBD vbd = Connection.Resolve(vbdRef); + var vbd = Connection.Resolve(vbdRef); if (vbd != null) { - VDI vdi = Connection.Resolve(vbd.VDI); + var vdi = Connection.Resolve(vbd.VDI); if (vdi != null) { - SR sr = Connection.Resolve(vdi.SR); + var sr = Connection.Resolve(vdi.SR); if (sr != null && !sr.shared) { - if (sr.content_type == SR.Content_Type_ISO) - { - return Messages.EJECT_YOUR_CD; - } - else - { - return Messages.VM_USES_LOCAL_STORAGE; - } + if (sr.content_type == SR.Content_Type_ISO) return Messages.EJECT_YOUR_CD; + + return Messages.VM_USES_LOCAL_STORAGE; } } } } + return ""; } @@ -511,21 +676,17 @@ public decimal GetRecommendedExportSpace(bool showHiddenVMs) { decimal totalSpace = 0; - foreach (VBD vbd in Connection.ResolveAll(VBDs)) - { + foreach (var vbd in Connection.ResolveAll(VBDs)) if (!vbd.IsCDROM()) { - VDI VDI = Connection.Resolve(vbd.VDI); - if (VDI != null && VDI.Show(showHiddenVMs)) + var vdi = Connection.Resolve(vbd.VDI); + if (vdi != null && vdi.Show(showHiddenVMs)) { - SR TheSR = Connection.Resolve(VDI.SR); - if (TheSR != null && !TheSR.IsToolsSR()) - { - totalSpace += VDI.virtual_size; - } + var theSr = Connection.Resolve(vdi.SR); + if (theSr != null && !theSr.IsToolsSR()) totalSpace += vdi.virtual_size; } } - } + return totalSpace; } @@ -560,130 +721,111 @@ public override int CompareTo(VM other) otherClass = 2; if (myClass != otherClass) - return (myClass - otherClass); - else - return base.CompareTo(other); + return myClass - otherClass; + return base.CompareTo(other); } /// - /// These are the operations that make us show the orange icon for the VM in the tree - /// and on the Memory tab. It's shorter to add the ones that cause problems. + /// These are the operations that make us show the orange icon for the VM in the tree + /// and on the Memory tab. It's shorter to add the ones that cause problems. /// public static bool is_lifecycle_operation(vm_operations op) { - return op != vm_operations.changing_dynamic_range && op != vm_operations.changing_static_range && op != vm_operations.changing_memory_limits; + return op != vm_operations.changing_dynamic_range && op != vm_operations.changing_static_range && + op != vm_operations.changing_memory_limits; } - private DateTime startuptime; - public DateTime GetBodgeStartupTime() { - return startuptime; + return _startupTime; } public void SetBodgeStartupTime(DateTime value) { - startuptime = value; + _startupTime = value; // This has an impact on the virt state of the VM as we allow a set amount of time for tools to show up before assuming unvirt NotifyPropertyChanged("virtualisation_status"); - if (VirtualizationTimer != null) - VirtualizationTimer.Stop(); + _virtualizationTimer?.Stop(); // 2 minutes before we give up plus some breathing space - VirtualizationTimer = new Timer(182000) {AutoReset = false}; - VirtualizationTimer.Elapsed += VirtualizationTimer_Elapsed; - VirtualizationTimer.Start(); + _virtualizationTimer = new Timer(182000) { AutoReset = false }; + _virtualizationTimer.Elapsed += VirtualizationTimer_Elapsed; + _virtualizationTimer.Start(); } - void VirtualizationTimer_Elapsed(object sender, ElapsedEventArgs e) + private void VirtualizationTimer_Elapsed(object sender, ElapsedEventArgs e) { NotifyPropertyChanged("virtualisation_status"); } - private Timer VirtualizationTimer = null; - - [Flags] - public enum VirtualisationStatus - { - NOT_INSTALLED = 0, - UNKNOWN = 1, - PV_DRIVERS_OUT_OF_DATE = 2, - IO_DRIVERS_INSTALLED = 4, - MANAGEMENT_INSTALLED = 8, - }; - - public string GetVirtualisationWarningMessages() + public string GetVirtualizationWarningMessages() { - VirtualisationStatus status = GetVirtualisationStatus(out _); + var status = GetVirtualizationStatus(out _); - if (status.HasFlag(VirtualisationStatus.IO_DRIVERS_INSTALLED) && status.HasFlag(VirtualisationStatus.MANAGEMENT_INSTALLED) - || status.HasFlag(VM.VirtualisationStatus.UNKNOWN)) - // calling function shouldn't send us here if tools are, or might be, present: used to assert here but it can sometimes happen (CA-51460) - return ""; + if ((status.HasFlag(VirtualizationStatus.IoDriversInstalled) && + status.HasFlag(VirtualizationStatus.ManagementInstalled)) + || status.HasFlag(VirtualizationStatus.Unknown)) + // calling function shouldn't send us here if tools are, or might be, present: used to assert here but it can sometimes happen (CA-51460) + return ""; - if (status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + if (status.HasFlag(VirtualizationStatus.PvDriversOutOfDate)) { - VM_guest_metrics guestMetrics = Connection.Resolve(guest_metrics); - if (guestMetrics != null - && guestMetrics.PV_drivers_version.ContainsKey("major") - && guestMetrics.PV_drivers_version.ContainsKey("minor")) - { - return string.Format(Messages.PV_DRIVERS_OUT_OF_DATE, BrandManager.VmTools, - guestMetrics.PV_drivers_version["major"], guestMetrics.PV_drivers_version["minor"]); - } - - return string.Format(Messages.PV_DRIVERS_OUT_OF_DATE_UNKNOWN_VERSION, BrandManager.VmTools); + var guestMetrics = Connection.Resolve(guest_metrics); + if (guestMetrics != null + && guestMetrics.PV_drivers_version.ContainsKey("major") + && guestMetrics.PV_drivers_version.ContainsKey("minor")) + return string.Format(Messages.PV_DRIVERS_OUT_OF_DATE, BrandManager.VmTools, + guestMetrics.PV_drivers_version["major"], guestMetrics.PV_drivers_version["minor"]); + + return string.Format(Messages.PV_DRIVERS_OUT_OF_DATE_UNKNOWN_VERSION, BrandManager.VmTools); } - return HasNewVirtualisationStates() + return HasNewVirtualizationStates() ? Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_NOT_INSTALLED : string.Format(Messages.PV_DRIVERS_NOT_INSTALLED, BrandManager.VmTools); } /// - /// Virtualization Status of the VM + /// Virtualization Status of the VM /// - /// /// - /// Following states are expected: - /// - /// For Non-Windows VMs and for Windows VMs pre-Dundee: - /// 0 = Not installed - /// 1 = Unknown - /// 2 = Out of date - /// 12 = Tools installed (Optimized) - /// - /// For Windows VMs on Dundee or higher: - /// 0 = Not installed - /// 1 = Unknown - /// 4 = I/O Optimized - /// 12 = I/O and Management installed + /// Following states are expected: + /// For Non-Windows VMs and for Windows VMs pre-Dundee: + /// 0 = Not installed + /// 1 = Unknown + /// 2 = Out of date + /// 12 = Tools installed (Optimized) + /// For Windows VMs on Dundee or higher: + /// 0 = Not installed + /// 1 = Unknown + /// 4 = I/O Optimized + /// 12 = I/O and Management installed /// - public VirtualisationStatus GetVirtualisationStatus(out string friendlyStatus) + public VirtualizationStatus GetVirtualizationStatus(out string friendlyStatus) { friendlyStatus = Messages.VIRTUALIZATION_UNKNOWN; if (Connection == null || power_state != vm_power_state.Running || Connection.Resolve(metrics) == null) - return VirtualisationStatus.UNKNOWN; + return VirtualizationStatus.Unknown; var vmGuestMetrics = Connection.Resolve(guest_metrics); var lessThanTwoMin = (DateTime.UtcNow - GetBodgeStartupTime()).TotalMinutes < 2; - if (HasNewVirtualisationStates()) + if (HasNewVirtualizationStates()) { - var flags = VirtualisationStatus.NOT_INSTALLED; + var flags = VirtualizationStatus.NotInstalled; if (vmGuestMetrics != null && vmGuestMetrics.PV_drivers_detected) - flags |= VirtualisationStatus.IO_DRIVERS_INSTALLED; + flags |= VirtualizationStatus.IoDriversInstalled; if (vmGuestMetrics != null && IntKey(vmGuestMetrics.other, "feature-static-ip-setting", 0) != 0) - flags |= VirtualisationStatus.MANAGEMENT_INSTALLED; + flags |= VirtualizationStatus.ManagementInstalled; - if (flags.HasFlag(VirtualisationStatus.IO_DRIVERS_INSTALLED | VirtualisationStatus.MANAGEMENT_INSTALLED)) + if (flags.HasFlag(VirtualizationStatus.IoDriversInstalled | VirtualizationStatus.ManagementInstalled)) friendlyStatus = Messages.VIRTUALIZATION_STATE_VM_IO_DRIVERS_AND_MANAGEMENT_AGENT_INSTALLED; - else if (flags.HasFlag(VirtualisationStatus.IO_DRIVERS_INSTALLED)) + else if (flags.HasFlag(VirtualizationStatus.IoDriversInstalled)) friendlyStatus = Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_NOT_INSTALLED; else if (lessThanTwoMin) - flags = VirtualisationStatus.UNKNOWN; + flags = VirtualizationStatus.Unknown; else friendlyStatus = string.Format(Messages.PV_DRIVERS_NOT_INSTALLED, BrandManager.VmTools); @@ -692,11 +834,13 @@ public VirtualisationStatus GetVirtualisationStatus(out string friendlyStatus) if (vmGuestMetrics == null || !vmGuestMetrics.PV_drivers_installed()) if (lessThanTwoMin) - return VirtualisationStatus.UNKNOWN; + { + return VirtualizationStatus.Unknown; + } else { friendlyStatus = string.Format(Messages.PV_DRIVERS_NOT_INSTALLED, BrandManager.VmTools); - return VirtualisationStatus.NOT_INSTALLED; + return VirtualizationStatus.NotInstalled; } if (!vmGuestMetrics.PV_drivers_version.TryGetValue("major", out var major)) @@ -707,28 +851,28 @@ public VirtualisationStatus GetVirtualisationStatus(out string friendlyStatus) if (!vmGuestMetrics.PV_drivers_up_to_date) { friendlyStatus = string.Format(Messages.VIRTUALIZATION_OUT_OF_DATE, $"{major}.{minor}"); - return VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE; + return VirtualizationStatus.PvDriversOutOfDate; } friendlyStatus = string.Format(Messages.VIRTUALIZATION_OPTIMIZED, $"{major}.{minor}"); - return VirtualisationStatus.IO_DRIVERS_INSTALLED | VirtualisationStatus.MANAGEMENT_INSTALLED; + return VirtualizationStatus.IoDriversInstalled | VirtualizationStatus.ManagementInstalled; } /// - /// Is this a Windows VM on Dundee or higher host? - /// We need to know this, because for those VMs virtualization status is defined differently. - /// This does not mean new(ly created) VM + /// Is this a Windows VM on Dundee or higher host? + /// We need to know this, because for those VMs virtualization status is defined differently. + /// This does not mean new(ly created) VM /// - public bool HasNewVirtualisationStates() + public bool HasNewVirtualizationStates() { return IsWindows(); } /// - /// Returns whether this VM support ballooning. - /// Real VMs support ballooning if tools are installed on a balloonable OS. - /// For templates we cannot tell whether tools are installed, so ballooning is - /// supported if and only if dynamic min != static_max (CA-34258/CA-34260). + /// Returns whether this VM support ballooning. + /// Real VMs support ballooning if tools are installed on a balloonable OS. + /// For templates we cannot tell whether tools are installed, so ballooning is + /// supported if and only if dynamic min != static_max (CA-34258/CA-34260). /// public bool SupportsBallooning() { @@ -743,7 +887,7 @@ public bool SupportsBallooning() } /// - /// Whether the VM uses ballooning (has different setting of dynamic_max and static_max) + /// Whether the VM uses ballooning (has different setting of dynamic_max and static_max) /// public bool UsesBallooning() { @@ -751,7 +895,7 @@ public bool UsesBallooning() } /// - /// Whether the VM should be shown to the user in the GUI. + /// Whether the VM should be shown to the user in the GUI. /// public override bool Show(bool showHiddenVMs) { @@ -765,11 +909,10 @@ public override bool Show(bool showHiddenVMs) return true; return !IsHidden(); - } /// - /// Returns whether the other_config.HideFromXenCenter flag is set to true. + /// Returns whether the other_config.HideFromXenCenter flag is set to true. /// public override bool IsHidden() { @@ -780,83 +923,26 @@ public bool HasNoDisksAndNoLocalCD() { if (Connection == null) return false; - foreach (VBD vbd in Connection.ResolveAll(VBDs)) + foreach (var vbd in Connection.ResolveAll(VBDs)) { - if (vbd.type == vbd_type.Disk) - { - return false; // we have a disk :( - } - else - { - VDI vdi = Connection.Resolve(vbd.VDI); - if (vdi == null) - continue; - SR sr = Connection.Resolve(vdi.SR); - if (sr == null || sr.shared) - continue; - return false; // we have a shared cd - } + if (vbd.type == vbd_type.Disk) return false; // we have a disk :( + + var vdi = Connection.Resolve(vbd.VDI); + if (vdi == null) + continue; + var sr = Connection.Resolve(vdi.SR); + if (sr == null || sr.shared) + continue; + return false; // we have a shared cd } + return true; // we have no disks hooray!! } - private const string P2V_SOURCE_MACHINE = "p2v_source_machine"; - private const string P2V_IMPORT_DATE = "p2v_import_date"; - public bool IsP2V() { - return other_config != null && other_config.ContainsKey(P2V_SOURCE_MACHINE) && other_config.ContainsKey(P2V_IMPORT_DATE); - } - - /// - /// List of distros that we treat as Linux/Non-Windows (written in the VM.guest_metrics - /// by the Linux Guest Agent after evaluating xe-linux-distribution) - /// - private static string[] linuxDistros = - { - "debian", "rhel", "fedora", "centos", "scientific", "oracle", "sles", - "lsb", "boot2docker", "freebsd", "ubuntu", "neokylin", "gooroom", "rocky" - }; - - /// - /// Sort in the following order: - /// 1) User Templates - /// 2) Windows VMs - /// 3) Other VMs (e.g. Linux . Names in alphabetical order) - /// 4) Citrix VMs (e.g. XenApp templates) - /// 5) Misc VMs - /// 6) Regular snapshots - /// 7) Snapshots from VMPP (CA-46206) - /// Last: Hidden VMs (only visible if "Show Hidden Objects" is on: see CA-39036). - /// - public enum VmTemplateType - { - NoTemplate = 0,//it's not a template - Custom = 1, - Windows = 2, - WindowsServer = 3, - LegacyWindows = 4, - Asianux = 5, - Centos = 6, - CoreOS = 7, - Debian = 8, - Gooroom = 9, - Linx = 10, - NeoKylin = 11, - Oracle = 12, - RedHat = 13, - Rocky = 14, - SciLinux = 15, - Suse = 16, - Turbo = 17, - Ubuntu = 18, - YinheKylin = 19, - Citrix = 20, - Solaris = 21, - Misc = 22, - Snapshot = 23, - SnapshotFromVmpp = 24, - Count = 25 //bump this if values are added + return other_config != null && other_config.ContainsKey(P2V_SOURCE_MACHINE) && + other_config.ContainsKey(P2V_IMPORT_DATE); } public VmTemplateType TemplateType() @@ -873,7 +959,7 @@ public VmTemplateType TemplateType() if (!DefaultTemplate()) return VmTemplateType.Custom; - string os = name_label.ToLowerInvariant(); + var os = name_label.ToLowerInvariant(); if (os.Contains("citrix")) return VmTemplateType.Citrix; @@ -958,8 +1044,6 @@ public VmDescriptionType DescriptionType() } } - public enum VmDescriptionType { None, ReadOnly, ReadWrite } - public override string Description() { // Don't i18n this @@ -978,7 +1062,9 @@ public override string Description() public string P2V_SourceMachine() { - return other_config != null && other_config.ContainsKey(P2V_SOURCE_MACHINE) ? other_config[P2V_SOURCE_MACHINE] : ""; + return other_config != null && other_config.ContainsKey(P2V_SOURCE_MACHINE) + ? other_config[P2V_SOURCE_MACHINE] + : ""; } public DateTime P2V_ImportDate() @@ -986,78 +1072,72 @@ public DateTime P2V_ImportDate() if (other_config == null || !other_config.ContainsKey(P2V_IMPORT_DATE)) return DateTime.MinValue; - string importDate = other_config[P2V_IMPORT_DATE]; + var importDate = other_config[P2V_IMPORT_DATE]; return Util.TryParseIso8601DateTime(importDate, out var result) ? result : DateTime.MinValue; } - public String GetOSName() + public string GetOSName() { - VM_guest_metrics guestMetrics = Connection.Resolve(guest_metrics); - if (guestMetrics == null) - return Messages.UNKNOWN; + var guestMetrics = Connection.Resolve(guest_metrics); - if (guestMetrics.os_version == null) + if (guestMetrics?.os_version == null) return Messages.UNKNOWN; if (!guestMetrics.os_version.ContainsKey("name")) return Messages.UNKNOWN; - String os_name = guestMetrics.os_version["name"]; + var osName = guestMetrics.os_version["name"]; // This hack is to make the windows names look nicer - int index = os_name.IndexOf("|"); + var index = osName.IndexOf("|"); if (index >= 1) - os_name = os_name.Substring(0, index); + osName = osName.Substring(0, index); // CA-9631: conform to MS trademark guidelines - if (os_name.StartsWith("Microsoft®")) + if (osName.StartsWith("Microsoft®")) { - if (os_name != "Microsoft®") - os_name = os_name.Substring(10).Trim(); + if (osName != "Microsoft®") + osName = osName.Substring(10).Trim(); } - else if (os_name.StartsWith("Microsoft")) + else if (osName.StartsWith("Microsoft")) { - if (os_name != "Microsoft") - os_name = os_name.Substring(9).Trim(); + if (osName != "Microsoft") + osName = osName.Substring(9).Trim(); } - if (os_name == "") + if (osName == "") return Messages.UNKNOWN; - else - return os_name; + return osName; } /// - /// Gets the time this VM started, in server time, UTC. Returns DateTime.MinValue if there are no VM_metrics - /// to read. + /// Gets the time this VM started, in server time, UTC. Returns DateTime.MinValue if there are no VM_metrics + /// to read. /// public DateTime GetStartTime() { - VM_metrics metrics = Connection.Resolve(this.metrics); + var metrics = Connection.Resolve(this.metrics); if (metrics == null) return DateTime.MinValue; return metrics.start_time; } - private static readonly DateTime Epoch = new DateTime(1970, 1, 1); public PrettyTimeSpan RunningTime() { if (power_state != vm_power_state.Running && power_state != vm_power_state.Paused && power_state != vm_power_state.Suspended) - { return null; - } - DateTime startTime = GetStartTime(); + var startTime = GetStartTime(); if (startTime == Epoch || startTime == DateTime.MinValue) return null; return new PrettyTimeSpan(DateTime.UtcNow - startTime - Connection.ServerTimeOffset); } /// - /// Returns DateTime.MinValue if the date is not present in other_config. + /// Returns DateTime.MinValue if the date is not present in other_config. /// public DateTime LastShutdownTime() { @@ -1067,37 +1147,31 @@ public DateTime LastShutdownTime() : DateTime.MinValue; } - /// - /// AlwaysRestartHighPriority and AlwaysRestart are replaced by Restart in Boston; we still keep them for backward compatibility - /// - public enum HA_Restart_Priority { AlwaysRestartHighPriority, AlwaysRestart, Restart, BestEffort, DoNotRestart }; - /// - /// An enum-ified version of ha_restart_priority: use this one instead. - /// NB setting this property does not change ha-always-run. + /// An enum-ified version of ha_restart_priority: use this one instead. + /// NB setting this property does not change ha-always-run. /// - public HA_Restart_Priority HARestartPriority() + public HaRestartPriority HARestartPriority() { - return StringToPriority(this.ha_restart_priority); + return StringToPriority(ha_restart_priority); } - public override string NameWithLocation() + public override string NameWithLocation() { - if (this.Connection != null) + if (Connection != null) { - if (this.IsRealVm()) - { - return base.NameWithLocation(); - } - else if (this.is_a_snapshot) + if (IsRealVm()) return base.NameWithLocation(); + + if (is_a_snapshot) { - var snapshotOf = this.Connection.Resolve(this.snapshot_of); + var snapshotOf = Connection.Resolve(snapshot_of); if (snapshotOf == null) return base.NameWithLocation(); return string.Format(Messages.SNAPSHOT_OF_TITLE, Name(), snapshotOf.Name(), LocationString()); } - else if (this.is_a_template) + + if (is_a_template) { if (Helpers.IsPool(Connection)) return string.Format(Messages.OBJECT_IN_POOL, Name(), Connection.Name); @@ -1111,147 +1185,138 @@ public override string NameWithLocation() internal override string LocationString() { - Host server = this.Home(); + var server = Home(); if (server != null) return string.Format(Messages.ON_SERVER, server); - Pool pool = Helpers.GetPool(this.Connection); + var pool = Helpers.GetPool(Connection); if (pool != null) return string.Format(Messages.IN_POOL, pool); return string.Empty; } - public static List GetAvailableRestartPriorities(IXenConnection connection) + public static List GetAvailableRestartPriorities(IXenConnection connection) { - var restartPriorities = new List(); - restartPriorities.Add(HA_Restart_Priority.Restart); - restartPriorities.Add(HA_Restart_Priority.BestEffort); - restartPriorities.Add(HA_Restart_Priority.DoNotRestart); + var restartPriorities = new List(); + restartPriorities.Add(HaRestartPriority.Restart); + restartPriorities.Add(HaRestartPriority.BestEffort); + restartPriorities.Add(HaRestartPriority.DoNotRestart); return restartPriorities; } /// - /// Returns true if VM's restart priority is AlwaysRestart or AlwaysRestartHighPriority. + /// Returns true if VM's restart priority is AlwaysRestart or AlwaysRestartHighPriority. /// public bool HaPriorityIsRestart() { return HaPriorityIsRestart(Connection, HARestartPriority()); } - public static bool HaPriorityIsRestart(IXenConnection connection, HA_Restart_Priority haRestartPriority) + public static bool HaPriorityIsRestart(IXenConnection connection, HaRestartPriority haRestartPriority) { - return haRestartPriority == HA_Restart_Priority.Restart; + return haRestartPriority == HaRestartPriority.Restart; } - public static HA_Restart_Priority HaHighestProtectionAvailable(IXenConnection connection) + public static HaRestartPriority HaHighestProtectionAvailable(IXenConnection connection) { - return HA_Restart_Priority.Restart; + return HaRestartPriority.Restart; } - public const string RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY = "0"; //only used for Pre-Boston pools - public const string RESTART_PRIORITY_ALWAYS_RESTART = "1"; //only used for Pre-Boston pools /// - /// This is the new "Restart" priority in Boston, and will replace RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY and RESTART_PRIORITY_ALWAYS_RESTART - /// - public const string RESTART_PRIORITY_RESTART = "restart"; - public const string RESTART_PRIORITY_BEST_EFFORT = "best-effort"; - public const string RESTART_PRIORITY_DO_NOT_RESTART = ""; - - /// - /// Parses a HA_Restart_Priority into a string the server understands. + /// Parses a HA_Restart_Priority into a string the server understands. /// /// /// - internal static string PriorityToString(HA_Restart_Priority priority) + internal static string PriorityToString(HaRestartPriority priority) { switch (priority) { - case HA_Restart_Priority.AlwaysRestartHighPriority: + case HaRestartPriority.AlwaysRestartHighPriority: return RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY; - case HA_Restart_Priority.AlwaysRestart: + case HaRestartPriority.AlwaysRestart: return RESTART_PRIORITY_ALWAYS_RESTART; - case HA_Restart_Priority.Restart: + case HaRestartPriority.Restart: return RESTART_PRIORITY_RESTART; - case HA_Restart_Priority.BestEffort: + case HaRestartPriority.BestEffort: return RESTART_PRIORITY_BEST_EFFORT; default: return RESTART_PRIORITY_DO_NOT_RESTART; } } - internal static HA_Restart_Priority StringToPriority(string priority) + internal static HaRestartPriority StringToPriority(string priority) { switch (priority) { case RESTART_PRIORITY_ALWAYS_RESTART_HIGH_PRIORITY: - return HA_Restart_Priority.AlwaysRestartHighPriority; + return HaRestartPriority.AlwaysRestartHighPriority; case RESTART_PRIORITY_RESTART: - return HA_Restart_Priority.Restart; + return HaRestartPriority.Restart; case RESTART_PRIORITY_DO_NOT_RESTART: - return HA_Restart_Priority.DoNotRestart; + return HaRestartPriority.DoNotRestart; case RESTART_PRIORITY_BEST_EFFORT: - return HA_Restart_Priority.BestEffort; + return HaRestartPriority.BestEffort; default: - return HA_Restart_Priority.AlwaysRestart; + return HaRestartPriority.AlwaysRestart; } } /// - /// Whether HA is capable of restarting this VM (i.e. the VM is not a template or control domain). + /// Whether HA is capable of restarting this VM (i.e. the VM is not a template or control domain). /// public bool HaCanProtect(bool showHiddenVMs) { return IsRealVm() && Show(showHiddenVMs); - } /// - /// True if this VM's ha_restart_priority is not "Do not restart" and its pool has ha_enabled true. + /// True if this VM's ha_restart_priority is not "Do not restart" and its pool has ha_enabled true. /// public bool HAIsProtected() { if (Connection == null) return false; - Pool myPool = Helpers.GetPoolOfOne(Connection); + var myPool = Helpers.GetPoolOfOne(Connection); if (myPool == null) return false; - return myPool.ha_enabled && HARestartPriority() != HA_Restart_Priority.DoNotRestart; + return myPool.ha_enabled && HARestartPriority() != HaRestartPriority.DoNotRestart; } /// - /// Calls set_ha_restart_priority + /// Calls set_ha_restart_priority /// /// - public static void SetHaRestartPriority(Session session, VM vm, HA_Restart_Priority priority) + public static void SetHaRestartPriority(Session session, VM vm, HaRestartPriority priority) { - VM.set_ha_restart_priority(session, vm.opaque_ref, PriorityToString(priority)); + set_ha_restart_priority(session, vm.opaque_ref, PriorityToString(priority)); } public bool AnyDiskFastClonable() { if (Connection == null) return false; - foreach (VBD vbd in Connection.ResolveAll(VBDs)) + foreach (var vbd in Connection.ResolveAll(VBDs)) { if (vbd.type != vbd_type.Disk) continue; - VDI vdi = Connection.Resolve(vbd.VDI); + var vdi = Connection.Resolve(vbd.VDI); if (vdi == null) continue; - SR sr = Connection.Resolve(vdi.SR); + var sr = Connection.Resolve(vdi.SR); if (sr == null) continue; - SM sm = SM.GetByType(Connection, sr.type); + var sm = SM.GetByType(Connection, sr.type); if (sm == null) continue; if (Array.IndexOf(sm.capabilities, "VDI_CLONE") != -1) return true; } + return false; } @@ -1259,18 +1324,19 @@ public bool HasAtLeastOneDisk() { if (Connection == null) return false; - foreach (VBD vbd in Connection.ResolveAll(VBDs)) + foreach (var vbd in Connection.ResolveAll(VBDs)) { if (vbd.type != vbd_type.Disk) continue; return true; } + return false; } /// - /// Checks whether the VM is the dom0 (the flag is_control_domain may also apply to other control domains) + /// Checks whether the VM is the dom0 (the flag is_control_domain may also apply to other control domains) /// public bool IsControlDomainZero(out Host host) { @@ -1298,16 +1364,14 @@ public bool IsSrDriverDomain(out SR sr) return false; foreach (var pbd in Connection.Cache.PBDs) - { if (pbd != null && - pbd.other_config.TryGetValue("storage_driver_domain", out string vmRef) && + pbd.other_config.TryGetValue("storage_driver_domain", out var vmRef) && vmRef == opaque_ref) { sr = Connection.Resolve(pbd.SR); if (sr != null) return true; } - } return false; } @@ -1317,27 +1381,15 @@ public bool IsRealVm() return !is_a_snapshot && !is_a_template && !is_control_domain; } - private bool _isBeingCreated; - [JsonIgnore] - public bool IsBeingCreated - { - get { return _isBeingCreated; } - set - { - _isBeingCreated = value; - NotifyPropertyChanged("IsBeingCreated"); - } - } - public XmlNode ProvisionXml() { try { - string xml = Get(other_config, "disks"); + var xml = Get(other_config, "disks"); if (string.IsNullOrEmpty(xml)) return null; - XmlDocument doc = new XmlDocument(); + var doc = new XmlDocument(); doc.LoadXml(xml); return doc.FirstChild; } @@ -1363,12 +1415,12 @@ public override string ToString() } /// - /// The name label of the VM's affinity server, or None if it is not set - /// (This is what the UI calls the "home server", but is not the same as VM.Home). + /// The name label of the VM's affinity server, or None if it is not set + /// (This is what the UI calls the "home server", but is not the same as VM.Home). /// public string AffinityServerString() { - Host host = Connection.Resolve(affinity); + var host = Connection.Resolve(affinity); if (host == null) return Messages.NONE; @@ -1382,31 +1434,22 @@ public bool HasProvisionXML() public bool BiosStringsCopied() { - if (DefaultTemplate()) - { - return false; - } + if (DefaultTemplate()) return false; - if (bios_strings.Count == 0) - { - return false; - } + if (bios_strings.Count == 0) return false; - bool value = bios_strings.ContainsKey("bios-vendor") && bios_strings["bios-vendor"] == "Xen" - && bios_strings.ContainsKey("system-manufacturer") && bios_strings["system-manufacturer"] == "Xen"; + var value = bios_strings.ContainsKey("bios-vendor") && bios_strings["bios-vendor"] == "Xen" + && bios_strings.ContainsKey("system-manufacturer") && + bios_strings["system-manufacturer"] == "Xen"; return !value; } public bool HasCD() { - foreach (var vbd in this.Connection.ResolveAll(this.VBDs)) - { + foreach (var vbd in Connection.ResolveAll(VBDs)) if (vbd.IsCDROM()) - { return true; - } - } return false; } @@ -1422,22 +1465,17 @@ public bool HasGPUPassthrough() var vGPUs = Connection.ResolveAll(VGPUs); return vGPUs.Any(vGPU => vGPU != null && vGPU.IsPassthrough()); } + return false; } public virtual IEnumerable SRs() { - List vbds = Connection.ResolveAll(VBDs); + var vbds = Connection.ResolveAll(VBDs); foreach (var vbd in vbds) { - if (vbd != null) - { - VDI vdi = vbd.Connection.Resolve(vbd.VDI); - if (vdi != null) - { - yield return vdi.Connection.Resolve(vdi.SR); - } - } + var vdi = vbd?.Connection.Resolve(vbd.VDI); + if (vdi != null) yield return vdi.Connection.Resolve(vdi.SR); } } @@ -1454,8 +1492,11 @@ public long GetCoresPerSocket() if (platform != null && platform.ContainsKey("cores-per-socket")) { long coresPerSocket; - return long.TryParse(platform["cores-per-socket"], out coresPerSocket) ? coresPerSocket : DEFAULT_CORES_PER_SOCKET; + return long.TryParse(platform["cores-per-socket"], out coresPerSocket) + ? coresPerSocket + : DEFAULT_CORES_PER_SOCKET; } + return DEFAULT_CORES_PER_SOCKET; } @@ -1471,12 +1512,13 @@ public long MaxCoresPerSocket() return homeServer.CoresPerSocket(); var maxCoresPerSocket = 0; - foreach (var host in this.Connection.Cache.Hosts) + foreach (var host in Connection.Cache.Hosts) { var coresPerSocket = host.CoresPerSocket(); if (coresPerSocket > maxCoresPerSocket) maxCoresPerSocket = coresPerSocket; } + return maxCoresPerSocket; } @@ -1494,20 +1536,23 @@ public static string ValidVCPUConfiguration(long noOfVCPUs, long coresPerSocket) if (noOfVCPUs / coresPerSocket > MAX_SOCKETS) return Messages.CPU_TOPOLOGY_INVALID_REASON_SOCKETS; } + return ""; } public string Topology() { var cores = GetCoresPerSocket(); - var sockets = ValidVCPUConfiguration(VCPUs_max, cores) == "" ? VCPUs_max/cores : 0; + var sockets = ValidVCPUConfiguration(VCPUs_max, cores) == "" ? VCPUs_max / cores : 0; return GetTopology(sockets, cores); } public static string GetTopology(long sockets, long cores) { if (sockets == 0) // invalid cores value - return cores == 1 ? string.Format(Messages.CPU_TOPOLOGY_STRING_INVALID_VALUE_1) : string.Format(Messages.CPU_TOPOLOGY_STRING_INVALID_VALUE, cores); + return cores == 1 + ? string.Format(Messages.CPU_TOPOLOGY_STRING_INVALID_VALUE_1) + : string.Format(Messages.CPU_TOPOLOGY_STRING_INVALID_VALUE, cores); if (sockets == 1 && cores == 1) return Messages.CPU_TOPOLOGY_STRING_1_SOCKET_1_CORE; if (sockets == 1) @@ -1531,7 +1576,8 @@ public bool IsEnlightened() public VDI CloudConfigDrive() { var vbds = Connection.ResolveAll(VBDs); - return vbds.Select(vbd => Connection.Resolve(vbd.VDI)).FirstOrDefault(vdi => vdi != null && vdi.IsCloudConfigDrive()); + return vbds.Select(vbd => Connection.Resolve(vbd.VDI)) + .FirstOrDefault(vdi => vdi != null && vdi.IsCloudConfigDrive()); } public bool CanHaveCloudConfigDrive() @@ -1544,19 +1590,19 @@ public bool CanHaveCloudConfigDrive() public VM_Docker_Info DockerInfo() { - string xml = Get(other_config, "docker_info"); + var xml = Get(other_config, "docker_info"); if (string.IsNullOrEmpty(xml)) return null; - VM_Docker_Info info = new VM_Docker_Info(xml); + var info = new VM_Docker_Info(xml); return info; } public VM_Docker_Version DockerVersion() { - string xml = Get(other_config, "docker_version"); + var xml = Get(other_config, "docker_version"); if (string.IsNullOrEmpty(xml)) return null; - VM_Docker_Version info = new VM_Docker_Version(xml); + var info = new VM_Docker_Version(xml); return info; } @@ -1566,7 +1612,7 @@ public bool ReadCachingEnabled() } /// - /// Return the list of VDIs that have Read Caching enabled + /// Return the list of VDIs that have Read Caching enabled /// public List ReadCachingVDIs() { @@ -1574,10 +1620,11 @@ public List ReadCachingVDIs() foreach (var vbd in Connection.ResolveAll(VBDs).Where(vbd => vbd != null && vbd.currently_attached)) { var vdi = Connection.Resolve(vbd.VDI); - var resident_host = Connection.Resolve(resident_on); - if (vdi != null && resident_host != null && vdi.ReadCachingEnabled(resident_host)) + var residentHost = Connection.Resolve(resident_on); + if (vdi != null && residentHost != null && vdi.ReadCachingEnabled(residentHost)) readCachingVdis.Add(vdi); } + return readCachingVdis; } @@ -1592,10 +1639,10 @@ public string ReadCachingDisabledReason() foreach (var vbd in Connection.ResolveAll(VBDs).Where(vbd => vbd != null && vbd.currently_attached)) { var vdi = Connection.Resolve(vbd.VDI); - var resident_host = Connection.Resolve(resident_on); - if (vdi != null && resident_host != null && !vdi.ReadCachingEnabled(resident_host)) + var residentHost = Connection.Resolve(resident_on); + if (vdi != null && residentHost != null && !vdi.ReadCachingEnabled(residentHost)) { - var reason = vdi.ReadCachingDisabledReason(resident_host); + var reason = vdi.ReadCachingDisabledReason(residentHost); if (reason > ans) ans = reason; } @@ -1606,8 +1653,7 @@ public string ReadCachingDisabledReason() case VDI.ReadCachingDisabledReasonCode.LICENSE_RESTRICTION: if (Helpers.FeatureForbidden(Connection, Host.RestrictReadCaching)) return Messages.VM_READ_CACHING_DISABLED_REASON_LICENSE; - else - return Messages.VM_READ_CACHING_DISABLED_REASON_PREV_LICENSE; + return Messages.VM_READ_CACHING_DISABLED_REASON_PREV_LICENSE; case VDI.ReadCachingDisabledReasonCode.SR_NOT_SUPPORTED: return Messages.VM_READ_CACHING_DISABLED_REASON_SR_TYPE; case VDI.ReadCachingDisabledReasonCode.NO_RO_IMAGE: @@ -1621,26 +1667,26 @@ public string ReadCachingDisabledReason() } /// - /// Whether the VM can be moved inside the pool (vdi copy + destroy) + /// Whether the VM can be moved inside the pool (vdi copy + destroy) /// public bool CanBeMoved() { if (SRs().Any(sr => sr != null && sr.HBALunPerVDI())) return false; - if (!is_a_template && !Locked && allowed_operations != null && allowed_operations.Contains(vm_operations.export) && power_state != vm_power_state.Suspended) - { + if (!is_a_template && !Locked && allowed_operations != null && + allowed_operations.Contains(vm_operations.export) && + power_state != vm_power_state.Suspended) return Connection.ResolveAll(VBDs).Find(v => v.GetIsOwner()) != null; - } return false; } /// - /// Returns whether this is a Windows VM by checking the distro value in the - /// guest_metrics before falling back to the viridian flag. The result may not be - /// correct at all times (a Linux distro can be detected if the guest agent is - /// running on the VM). It is more reliable if the VM has already booted once, and - /// also works for the "Other Install Media" template and unbooted VMs made from it. + /// Returns whether this is a Windows VM by checking the distro value in the + /// guest_metrics before falling back to the viridian flag. The result may not be + /// correct at all times (a Linux distro can be detected if the guest agent is + /// running on the VM). It is more reliable if the VM has already booted once, and + /// also works for the "Other Install Media" template and unbooted VMs made from it. /// public bool IsWindows() { @@ -1662,7 +1708,7 @@ private static bool CanTreatAsNonWindows(VM_guest_metrics guestMetrics) return false; if (guestMetrics.os_version.TryGetValue("distro", out var distro) && - !string.IsNullOrEmpty(distro) && linuxDistros.Contains(distro.ToLowerInvariant())) + !string.IsNullOrEmpty(distro) && LinuxDistros.Contains(distro.ToLowerInvariant())) return true; if (guestMetrics.os_version.TryGetValue("uname", out var uname) && @@ -1676,12 +1722,13 @@ private VM_guest_metrics GuestMetricsFromLastBootedRecord() { if (!string.IsNullOrEmpty(last_booted_record)) { - Regex regex = new Regex("'guest_metrics' +'(OpaqueRef:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})'"); + var regex = new Regex( + "'guest_metrics' +'(OpaqueRef:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})'"); var v = regex.Match(last_booted_record); if (v.Success) { - string s = v.Groups[1].ToString(); + var s = v.Groups[1].ToString(); return Connection.Resolve(new XenRef(s)); } } @@ -1691,19 +1738,19 @@ private VM_guest_metrics GuestMetricsFromLastBootedRecord() public bool WindowsUpdateCapable() { - return this.has_vendor_device && this.IsWindows(); + return has_vendor_device && IsWindows(); } /// - /// Returns the VM IP address for SSH login. + /// Returns the VM IP address for SSH login. /// public string IPAddressForSSH() { - List ipAddresses = new List(); + var ipAddresses = new List(); - if (!this.is_control_domain) //vm + if (!is_control_domain) //vm { - List vifs = this.Connection.ResolveAll(this.VIFs); + var vifs = Connection.ResolveAll(VIFs); vifs.Sort(); foreach (var vif in vifs) @@ -1720,25 +1767,22 @@ public string IPAddressForSSH() } else //control domain { - List pifList = new List(this.Connection.Cache.PIFs); + var pifList = new List(Connection.Cache.PIFs); pifList.Sort(); // This sort ensures that the primary PIF comes before other management PIFs - foreach (PIF pif in pifList) + foreach (var pif in pifList) { - if (pif.host.opaque_ref != this.resident_on.opaque_ref || !pif.currently_attached) + if (pif.host.opaque_ref != resident_on.opaque_ref || !pif.currently_attached) continue; - if (pif.IsManagementInterface(false)) - { - ipAddresses.Add(pif.IP); - } + if (pif.IsManagementInterface(false)) ipAddresses.Add(pif.IP); } } //find first IPv4 address and return it - we would use it if there is one IPAddress addr; - foreach (string addrString in ipAddresses) - if (IPAddress.TryParse(addrString, out addr) && addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + foreach (var addrString in ipAddresses) + if (IPAddress.TryParse(addrString, out addr) && addr.AddressFamily == AddressFamily.InterNetwork) return addrString; //return the first address (this will not be IPv4) @@ -1766,12 +1810,13 @@ public PVS_proxy PvsProxy() public bool UsingUpstreamQemu() { - return (platform != null) && - platform.ContainsKey("device-model") && - platform["device-model"] == "qemu-upstream-compat"; + return platform != null && + platform.ContainsKey("device-model") && + platform["device-model"] == "qemu-upstream-compat"; } + /// - /// Whether the VM's boot mode can be changed. A VM's boot mode cannot be changed once the VM has been started. + /// Whether the VM's boot mode can be changed. A VM's boot mode cannot be changed once the VM has been started. /// public bool CanChangeBootMode() { @@ -1796,7 +1841,7 @@ public bool CanAddVtpm(out string cannotReason) cannotReason = string.Format(Messages.VTPM_MAX_REACHED, MAX_ALLOWED_VTPMS); return false; } - + if (power_state != vm_power_state.Halted) { cannotReason = Messages.VTPM_POWER_STATE_WRONG_ATTACH; @@ -1818,12 +1863,46 @@ public bool CanRemoveVtpm(out string cannotReason) return true; } + + #region Boot Mode + + public bool IsDefaultBootModeUefi() + { + var firmware = Get(HVM_boot_params, "firmware")?.Trim().ToLower(); + return firmware == "uefi"; + } + + public string GetSecureBootMode() + { + return Get(platform, "secureboot")?.Trim().ToLower(); + } + + public bool SupportsUefiBoot() + { + return GetRecommendationByField("supports-uefi") == "yes"; + } + + public bool SupportsSecureUefiBoot() + { + return GetRecommendationByField("supports-secure-boot") == "yes"; + } + + private string GetRecommendationByField(string fieldName) + { + var xd = GetRecommendations(); + + var xn = xd?.SelectSingleNode(@"restrictions/restriction[@field='" + fieldName + "']"); + + return xn?.Attributes?["value"]?.Value ?? string.Empty; + } + + #endregion } public struct VMStartupOptions { public long Order, StartDelay; - public VM.HA_Restart_Priority? HaRestartPriority; + public VM.HaRestartPriority? HaRestartPriority; public VMStartupOptions(long order, long startDelay) { @@ -1832,7 +1911,7 @@ public VMStartupOptions(long order, long startDelay) HaRestartPriority = null; } - public VMStartupOptions(long order, long startDelay, VM.HA_Restart_Priority haRestartPriority) + public VMStartupOptions(long order, long startDelay, VM.HaRestartPriority haRestartPriority) { Order = order; StartDelay = startDelay; @@ -1840,7 +1919,12 @@ public VMStartupOptions(long order, long startDelay, VM.HA_Restart_Priority haRe } } - public enum VmBootMode { Bios, Uefi, SecureUefi } + public enum VmBootMode + { + Bios, + Uefi, + SecureUefi + } public static class BootModeExtensions { @@ -1859,4 +1943,4 @@ public static string StringOf(this VmBootMode mode) } } } -} +} \ No newline at end of file diff --git a/XenModel/XenSearch/Common.cs b/XenModel/XenSearch/Common.cs index f21a7c42bf..6a8f9b94fb 100644 --- a/XenModel/XenSearch/Common.cs +++ b/XenModel/XenSearch/Common.cs @@ -178,9 +178,9 @@ public class PropertyAccessors private static Dictionary> properties = new Dictionary>(); public static readonly Dictionary VM_power_state_i18n = new Dictionary(); - public static readonly Dictionary VirtualisationStatus_i18n = new Dictionary(); + public static readonly Dictionary VirtualisationStatus_i18n = new Dictionary(); public static readonly Dictionary ObjectTypes_i18n = new Dictionary(); - public static readonly Dictionary HARestartPriority_i18n = new Dictionary(); + public static readonly Dictionary HARestartPriority_i18n = new Dictionary(); public static readonly Dictionary SRType_i18n = new Dictionary(); public static readonly Dictionary PropertyNames_i18n = new Dictionary(); @@ -198,12 +198,12 @@ static PropertyAccessors() foreach (SR.SRTypes type in Enum.GetValues(typeof(SR.SRTypes))) SRType_i18n[SR.GetFriendlyTypeName(type)] = type; - VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_NOT_OPTIMIZED] = VM.VirtualisationStatus.NOT_INSTALLED; - VirtualisationStatus_i18n[Messages.OUT_OF_DATE] = VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE; - VirtualisationStatus_i18n[Messages.UNKNOWN] = VM.VirtualisationStatus.UNKNOWN; - VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_IO_OPTIMIZED_ONLY] = VM.VirtualisationStatus.IO_DRIVERS_INSTALLED; - VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_INSTALLED_ONLY] = VM.VirtualisationStatus.MANAGEMENT_INSTALLED; - VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_OPTIMIZED] = VM.VirtualisationStatus.IO_DRIVERS_INSTALLED | VM.VirtualisationStatus.MANAGEMENT_INSTALLED; + VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_NOT_OPTIMIZED] = VM.VirtualizationStatus.NotInstalled; + VirtualisationStatus_i18n[Messages.OUT_OF_DATE] = VM.VirtualizationStatus.PvDriversOutOfDate; + VirtualisationStatus_i18n[Messages.UNKNOWN] = VM.VirtualizationStatus.Unknown; + VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_IO_OPTIMIZED_ONLY] = VM.VirtualizationStatus.IoDriversInstalled; + VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_MANAGEMENT_AGENT_INSTALLED_ONLY] = VM.VirtualizationStatus.ManagementInstalled; + VirtualisationStatus_i18n[Messages.VIRTUALIZATION_STATE_VM_OPTIMIZED] = VM.VirtualizationStatus.IoDriversInstalled | VM.VirtualizationStatus.ManagementInstalled; ObjectTypes_i18n[Messages.VMS] = ObjectTypes.VM; ObjectTypes_i18n[string.Format(Messages.XENSERVER_TEMPLATES, BrandManager.ProductBrand)] = ObjectTypes.DefaultTemplate; @@ -220,7 +220,7 @@ static PropertyAccessors() ObjectTypes_i18n[Messages.VM_APPLIANCE] = ObjectTypes.Appliance; - foreach (VM.HA_Restart_Priority p in VM.GetAvailableRestartPriorities(null)) //CA-57600 - From Boston onwards, the HA restart priorities list contains Restart instead of AlwaysRestartHighPriority and AlwaysRestart + foreach (VM.HaRestartPriority p in VM.GetAvailableRestartPriorities(null)) //CA-57600 - From Boston onwards, the HA restart priorities list contains Restart instead of AlwaysRestartHighPriority and AlwaysRestart { HARestartPriority_i18n[Helpers.RestartPriorityI18n(p)] = p; } @@ -284,11 +284,11 @@ static PropertyAccessors() property_types.Add(PropertyNames.host, typeof(Host)); property_types.Add(PropertyNames.os_name, typeof(string)); property_types.Add(PropertyNames.power_state, typeof(vm_power_state)); - property_types.Add(PropertyNames.virtualisation_status, typeof(VM.VirtualisationStatus)); + property_types.Add(PropertyNames.virtualisation_status, typeof(VM.VirtualizationStatus)); property_types.Add(PropertyNames.type, typeof(ObjectTypes)); property_types.Add(PropertyNames.networks, typeof(XenAPI.Network)); property_types.Add(PropertyNames.storage, typeof(SR)); - property_types.Add(PropertyNames.ha_restart_priority, typeof(VM.HA_Restart_Priority)); + property_types.Add(PropertyNames.ha_restart_priority, typeof(VM.HaRestartPriority)); property_types.Add(PropertyNames.read_caching_enabled, typeof(bool)); property_types.Add(PropertyNames.appliance, typeof(VM_appliance)); property_types.Add(PropertyNames.tags, typeof(string)); @@ -304,7 +304,7 @@ static PropertyAccessors() properties[PropertyNames.os_name] = o => o is VM vm && vm.IsRealVm() ? vm.GetOSName() : null; properties[PropertyNames.power_state] = o => o is VM vm && vm.IsRealVm() ? (IComparable)vm.power_state : null; properties[PropertyNames.vendor_device_state] = o => o is VM vm && vm.IsRealVm() ? (bool?)vm.WindowsUpdateCapable() : null; - properties[PropertyNames.virtualisation_status] = o => o is VM vm && vm.IsRealVm() ? (IComparable)vm.GetVirtualisationStatus(out _) : null; + properties[PropertyNames.virtualisation_status] = o => o is VM vm && vm.IsRealVm() ? (IComparable)vm.GetVirtualizationStatus(out _) : null; properties[PropertyNames.start_time] = o => o is VM vm && vm.IsRealVm() ? (DateTime?)vm.GetStartTime() : null; properties[PropertyNames.read_caching_enabled] = o => o is VM vm && vm.IsRealVm() ? (bool?)vm.ReadCachingEnabled() : null; @@ -343,7 +343,7 @@ static PropertyAccessors() { Pool pool = Helpers.GetPool(vm.Connection); if (pool != null && pool.ha_enabled) - return vm.HaPriorityIsRestart() ? VM.HA_Restart_Priority.Restart : vm.HARestartPriority(); + return vm.HaPriorityIsRestart() ? VM.HaRestartPriority.Restart : vm.HARestartPriority(); // CA-57600 - From Boston onwards, the HA_restart_priority enum contains Restart instead of // AlwaysRestartHighPriority and AlwaysRestart. When searching in a pre-Boston pool for VMs @@ -465,7 +465,7 @@ private static IComparable MemoryTextProperty(IXenObject o) { return vm.IsRealVm() && vm.power_state == vm_power_state.Running && - vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED) + vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.ManagementInstalled) ? PropertyAccessorHelper.vmMemoryUsageString(vm) : null; } @@ -487,7 +487,7 @@ private static IComparable MemoryRankProperty(IXenObject o) { return vm.IsRealVm() && vm.power_state == vm_power_state.Running && - vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED) + vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.ManagementInstalled) ? (IComparable)PropertyAccessorHelper.vmMemoryUsageRank(vm) : null; } @@ -509,7 +509,7 @@ private static IComparable MemoryValueProperty(IXenObject o) { return vm.IsRealVm() && vm.power_state == vm_power_state.Running && - vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.MANAGEMENT_INSTALLED) + vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.ManagementInstalled) ? (IComparable)PropertyAccessorHelper.vmMemoryUsageValue(vm) : null; } @@ -531,7 +531,7 @@ private static IComparable NetworkTextProperty(IXenObject o) { return vm.IsRealVm() && vm.power_state == vm_power_state.Running && - vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED) + vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled) ? PropertyAccessorHelper.vmNetworkUsageString(vm) : null; } @@ -549,7 +549,7 @@ private static IComparable DiskTextProperty(IXenObject o) return o is VM vm && vm.IsRealVm() && vm.power_state == vm_power_state.Running && - vm.GetVirtualisationStatus(out _).HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED) + vm.GetVirtualizationStatus(out _).HasFlag(VM.VirtualizationStatus.IoDriversInstalled) ? PropertyAccessorHelper.vmDiskUsageString(vm) : null; } @@ -1007,12 +1007,12 @@ public static object GetImagesFor(PropertyNames p) }); case PropertyNames.virtualisation_status: - return (Func)(status => + return (Func)(status => { - if (status.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED | VM.VirtualisationStatus.MANAGEMENT_INSTALLED)) + if (status.HasFlag(VM.VirtualizationStatus.IoDriversInstalled | VM.VirtualizationStatus.ManagementInstalled)) return Icons.ToolInstalled; - if (status.HasFlag(VM.VirtualisationStatus.PV_DRIVERS_OUT_OF_DATE)) + if (status.HasFlag(VM.VirtualizationStatus.PvDriversOutOfDate)) return Icons.ToolsOutOfDate; return Icons.ToolsNotInstalled; @@ -1025,7 +1025,7 @@ public static object GetImagesFor(PropertyNames p) return (Func)(_ => Icons.Tag); case PropertyNames.ha_restart_priority: - return (Func)(_ => Icons.HA); + return (Func)(_ => Icons.HA); case PropertyNames.read_caching_enabled: return (Func)(_ => Icons.VDI); diff --git a/XenModel/XenSearch/Search.cs b/XenModel/XenSearch/Search.cs index ee6220f104..e2c7e149ff 100644 --- a/XenModel/XenSearch/Search.cs +++ b/XenModel/XenSearch/Search.cs @@ -785,9 +785,9 @@ private static void InitDefaultSearches() new GroupQuery( new QueryFilter[] { new EnumPropertyQuery(PropertyNames.power_state, vm_power_state.Running, true), - new EnumPropertyQuery(PropertyNames.virtualisation_status, VM.VirtualisationStatus.IO_DRIVERS_INSTALLED | VM.VirtualisationStatus.MANAGEMENT_INSTALLED, false) + new EnumPropertyQuery(PropertyNames.virtualisation_status, VM.VirtualizationStatus.IoDriversInstalled | VM.VirtualizationStatus.ManagementInstalled, false) }, GroupQuery.GroupQueryType.And)), - new PropertyGrouping(PropertyNames.virtualisation_status, null), + new PropertyGrouping(PropertyNames.virtualisation_status, null), string.Format(Messages.DEFAULT_SEARCH_VMS_WO_XS_TOOLS, BrandManager.VmTools), "dead-beef-1234-vmswotools", true ); From 64c8f439618849cce3c216be23cd3824a51b0028 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Thu, 14 Sep 2023 14:49:46 +0800 Subject: [PATCH 02/31] CP-44372: Integrate NRPE UI with backend interface --- XenAdmin/Dialogs/PropertiesDialog.cs | 6 + .../SettingsPanels/NRPEEditPage.CheckGroup.cs | 273 ++++++++ .../SettingsPanels/NRPEEditPage.Designer.cs | 229 +++++++ XenAdmin/SettingsPanels/NRPEEditPage.cs | 397 +++++++++++ XenAdmin/SettingsPanels/NRPEEditPage.resx | 615 ++++++++++++++++++ XenAdmin/XenAdmin.csproj | 14 + XenModel/Actions/Host/NRPEUpdateAction.cs | 191 ++++++ XenModel/Messages.Designer.cs | 234 +++++++ XenModel/Messages.resx | 78 +++ XenModel/NRPE/NRPEHostConfiguration.cs | 109 ++++ XenModel/XenModel.csproj | 2 + 11 files changed, 2148 insertions(+) create mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs create mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs create mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.cs create mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.resx create mode 100644 XenModel/Actions/Host/NRPEUpdateAction.cs create mode 100644 XenModel/NRPE/NRPEHostConfiguration.cs diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index 94f72f9f40..a6dda37d70 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -82,6 +82,7 @@ public partial class PropertiesDialog : VerticallyTabbedDialog private ClusteringEditPage ClusteringEditPage; private SrReadCachingEditPage SrReadCachingEditPage; private PoolAdvancedEditPage _poolAdvancedEditPage; + private NRPEEditPage NRPEEditPage; #endregion private readonly IXenObject _xenObjectBefore, _xenObjectCopy; @@ -317,6 +318,11 @@ private void Build() dialog.ShowDialog(Program.MainWindow); } } + if (isHost || isPool) + { + NRPEEditPage = new NRPEEditPage(isHost); + ShowTab(NRPEEditPage); + } } finally { diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs new file mode 100644 index 0000000000..3a779a3bdb --- /dev/null +++ b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs @@ -0,0 +1,273 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System.Drawing; +using System.Windows.Forms; + +namespace XenAdmin.SettingsPanels +{ + public partial class NRPEEditPage + { + + public class CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "80"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "90"; + + private readonly decimal THRESHOLD_MINIMUM = 0.1M; + private readonly decimal THRESHOLD_MAXIMUM = 100M; + + private string name; + private string warningThresholdDefault; + private string criticalThresholdDefault; + + protected DataGridViewRow checkThresholdRow; + protected DataGridViewTextBoxCell nameCell; + protected DataGridViewTextBoxCell warningThresholdCell; + protected DataGridViewTextBoxCell criticalThresholdCell; + + public string Name { get => name; set => name = value; } + public string WarningThresholdDefault { get => warningThresholdDefault; set => warningThresholdDefault = value; } + public string CriticalThresholdDefault { get => criticalThresholdDefault; set => criticalThresholdDefault = value; } + public DataGridViewRow CheckThresholdRow { get => checkThresholdRow; set => checkThresholdRow = value; } + public DataGridViewTextBoxCell NameCell { get => nameCell; set => nameCell = value; } + public DataGridViewTextBoxCell WarningThresholdCell { get => warningThresholdCell; set => warningThresholdCell = value; } + public DataGridViewTextBoxCell CriticalThresholdCell { get => criticalThresholdCell; set => criticalThresholdCell = value; } + + public CheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) + { + InitCheckGroup(name, labelName, warningThresholdDefaultValue, criticalThresholdDefaultValue); + } + + public CheckGroup(string name, string labelName) + { + InitCheckGroup(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD); + } + + private void InitCheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) + { + Name = name; + nameCell = new DataGridViewTextBoxCell { Value = labelName }; + warningThresholdDefault = warningThresholdDefaultValue; + criticalThresholdDefault = criticalThresholdDefaultValue; + warningThresholdCell = new DataGridViewTextBoxCell { Value = warningThresholdDefaultValue }; + criticalThresholdCell = new DataGridViewTextBoxCell { Value = criticalThresholdDefaultValue }; + checkThresholdRow = new DataGridViewRow(); + checkThresholdRow.Cells.AddRange(nameCell, warningThresholdCell, criticalThresholdCell); + checkThresholdRow.DefaultCellStyle.Format = "N2"; + checkThresholdRow.DefaultCellStyle.NullValue = 0; + warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + } + + public void UpdateThreshold(string warningThreshold, string criticalThreshold) + { + warningThresholdCell.Value = warningThreshold; + criticalThresholdCell.Value = criticalThreshold; + warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + + public virtual bool CheckValue() + { + warningThresholdCell.ErrorText = ""; + criticalThresholdCell.ErrorText = ""; + checkThresholdRow.DataGridView.ShowCellToolTips = false; + + if (IsEmptyForPool()) + { + return true; + } + + if (CheckEachValue(warningThresholdCell) && + CheckEachValue(criticalThresholdCell) && + CompareWarningAndCritical() && + CheckModifyAllForPool()) + { + return true; + } + + checkThresholdRow.DataGridView.ShowCellToolTips = true; + return false; + } + + private bool IsEmptyForPool() + { + return warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)); + } + + protected virtual bool CheckEachValue(DataGridViewTextBoxCell cell) + { + string thresholdStr = cell.Value.ToString().Trim(); + if (thresholdStr.Equals("")) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + if (!decimal.TryParse(thresholdStr, out decimal threshold)) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_NUMBER); + return false; + } + if (threshold < THRESHOLD_MINIMUM || threshold > THRESHOLD_MAXIMUM) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_RANGE_ERROR, THRESHOLD_MINIMUM, THRESHOLD_MAXIMUM); + return false; + } + cell.ErrorText = ""; + return true; + } + + protected virtual bool CompareWarningAndCritical() + { + decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal < criticalDecimal) + { + warningThresholdCell.ErrorText = ""; + return true; + } + else + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + + private bool CheckModifyAllForPool() + { + if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) + { + criticalThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + else if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + return true; + } + } + + public class FreeCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "20"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "10"; + + public FreeCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + + protected override bool CompareWarningAndCritical() + { + decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + warningThresholdCell.ErrorText = ""; + return true; + } + else + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL); + return false; + } + } + + } + + public class HostLoadCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "3"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "4"; + + public HostLoadCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + } + + public class Dom0LoadCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "2.7,2.6,2.5"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "3.2,3.1,3"; + + public Dom0LoadCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + + protected override bool CompareWarningAndCritical() + { + string[] warningArray = warningThresholdCell.Value.ToString().Split(','); + string[] criticalArray = criticalThresholdCell.Value.ToString().Split(','); + for (int i = 0; i < 3; i++) + { + decimal.TryParse(warningArray[i].Trim(), out decimal warningDecimal); + decimal.TryParse(criticalArray[i].Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + warningThresholdCell.ErrorText = ""; + return true; + } + + protected override bool CheckEachValue(DataGridViewTextBoxCell cell) + { + checkThresholdRow.DataGridView.ShowCellToolTips = true; + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS); + string[] loadArray = cell.Value.ToString().Split(','); + if (loadArray.Length != 3) + { + return false; + } + foreach (string load in loadArray) + { + bool isDecimal = decimal.TryParse(load, out _); + if (!isDecimal) + { + return false; + } + } + cell.ErrorText = ""; + checkThresholdRow.DataGridView.ShowCellToolTips = false; + return true; + } + } + } +} diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs new file mode 100644 index 0000000000..d5bcfdf005 --- /dev/null +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -0,0 +1,229 @@ +using System.Windows.Forms; +using DataGridView = System.Windows.Forms.DataGridView; + +namespace XenAdmin.SettingsPanels +{ + partial class NRPEEditPage + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NRPEEditPage)); + System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); + this.NRPETableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + this.PoolTipsTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + this.PoolTipsPicture = new System.Windows.Forms.PictureBox(); + this.PoolTipsLabel = new System.Windows.Forms.Label(); + this.DescLabel = new System.Windows.Forms.Label(); + this.GeneralConfigureGroupBox = new System.Windows.Forms.GroupBox(); + this.GeneralConfigTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); + this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); + this.AllowHostsLabel = new System.Windows.Forms.Label(); + this.AllowHostsTextBox = new System.Windows.Forms.TextBox(); + this.DebugLogCheckBox = new System.Windows.Forms.CheckBox(); + this.SslDebugLogCheckBox = new System.Windows.Forms.CheckBox(); + this.CheckDataGridView = new System.Windows.Forms.DataGridView(); + this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.NRPETableLayoutPanel.SuspendLayout(); + this.PoolTipsTableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PoolTipsPicture)).BeginInit(); + this.GeneralConfigureGroupBox.SuspendLayout(); + this.GeneralConfigTableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); + this.SuspendLayout(); + // + // NRPETableLayoutPanel + // + resources.ApplyResources(this.NRPETableLayoutPanel, "NRPETableLayoutPanel"); + this.NRPETableLayoutPanel.Controls.Add(this.PoolTipsTableLayoutPanel, 0, 4); + this.NRPETableLayoutPanel.Controls.Add(this.DescLabel, 0, 0); + this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 1); + this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 2); + this.NRPETableLayoutPanel.Name = "NRPETableLayoutPanel"; + // + // PoolTipsTableLayoutPanel + // + resources.ApplyResources(this.PoolTipsTableLayoutPanel, "PoolTipsTableLayoutPanel"); + this.PoolTipsTableLayoutPanel.Controls.Add(this.PoolTipsPicture, 0, 0); + this.PoolTipsTableLayoutPanel.Controls.Add(this.PoolTipsLabel, 1, 0); + this.PoolTipsTableLayoutPanel.Name = "PoolTipsTableLayoutPanel"; + // + // PoolTipsPicture + // + resources.ApplyResources(this.PoolTipsPicture, "PoolTipsPicture"); + this.PoolTipsPicture.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; + this.PoolTipsPicture.Name = "PoolTipsPicture"; + this.PoolTipsPicture.TabStop = false; + // + // PoolTipsLabel + // + resources.ApplyResources(this.PoolTipsLabel, "PoolTipsLabel"); + this.PoolTipsLabel.Name = "PoolTipsLabel"; + // + // DescLabel + // + resources.ApplyResources(this.DescLabel, "DescLabel"); + this.DescLabel.Name = "DescLabel"; + // + // GeneralConfigureGroupBox + // + resources.ApplyResources(this.GeneralConfigureGroupBox, "GeneralConfigureGroupBox"); + this.GeneralConfigureGroupBox.Controls.Add(this.GeneralConfigTableLayoutPanel); + this.GeneralConfigureGroupBox.Name = "GeneralConfigureGroupBox"; + this.GeneralConfigureGroupBox.TabStop = false; + // + // GeneralConfigTableLayoutPanel + // + resources.ApplyResources(this.GeneralConfigTableLayoutPanel, "GeneralConfigTableLayoutPanel"); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 1); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsLabel, 0, 2); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsTextBox, 1, 2); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.DebugLogCheckBox, 0, 3); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.SslDebugLogCheckBox, 0, 4); + this.GeneralConfigTableLayoutPanel.Name = "GeneralConfigTableLayoutPanel"; + // + // EnableNRPECheckBox + // + resources.ApplyResources(this.EnableNRPECheckBox, "EnableNRPECheckBox"); + this.GeneralConfigTableLayoutPanel.SetColumnSpan(this.EnableNRPECheckBox, 2); + this.EnableNRPECheckBox.Name = "EnableNRPECheckBox"; + this.EnableNRPECheckBox.UseVisualStyleBackColor = true; + this.EnableNRPECheckBox.CheckedChanged += new System.EventHandler(this.EnableNRPECheckBox_CheckedChanged); + // + // AllowHostsLabel + // + resources.ApplyResources(this.AllowHostsLabel, "AllowHostsLabel"); + this.AllowHostsLabel.Name = "AllowHostsLabel"; + // + // AllowHostsTextBox + // + resources.ApplyResources(this.AllowHostsTextBox, "AllowHostsTextBox"); + this.AllowHostsTextBox.Name = "AllowHostsTextBox"; + // + // DebugLogCheckBox + // + resources.ApplyResources(this.DebugLogCheckBox, "DebugLogCheckBox"); + this.GeneralConfigTableLayoutPanel.SetColumnSpan(this.DebugLogCheckBox, 2); + this.DebugLogCheckBox.Name = "DebugLogCheckBox"; + this.DebugLogCheckBox.UseVisualStyleBackColor = true; + // + // SslDebugLogCheckBox + // + resources.ApplyResources(this.SslDebugLogCheckBox, "SslDebugLogCheckBox"); + this.GeneralConfigTableLayoutPanel.SetColumnSpan(this.SslDebugLogCheckBox, 2); + this.SslDebugLogCheckBox.Name = "SslDebugLogCheckBox"; + this.SslDebugLogCheckBox.UseVisualStyleBackColor = true; + // + // CheckDataGridView + // + this.CheckDataGridView.AllowUserToAddRows = false; + this.CheckDataGridView.AllowUserToDeleteRows = false; + this.CheckDataGridView.AllowUserToResizeRows = false; + resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); + this.CheckDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.CheckDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; + this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.CheckDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; + this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.CheckColumn, + this.WarningThresholdColumn, + this.CriticalThresholdColumn}); + this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; + this.CheckDataGridView.EnableHeadersVisualStyles = false; + this.CheckDataGridView.MultiSelect = false; + this.CheckDataGridView.Name = "CheckDataGridView"; + this.CheckDataGridView.RowHeadersVisible = false; + this.CheckDataGridView.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.CheckDataGridView_BeginEdit); + this.CheckDataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.CheckDataGridView_EndEdit); + // + // CheckColumn + // + this.CheckColumn.FillWeight = 103.4483F; + resources.ApplyResources(this.CheckColumn, "CheckColumn"); + this.CheckColumn.Name = "CheckColumn"; + this.CheckColumn.ReadOnly = true; + // + // WarningThresholdColumn + // + dataGridViewCellStyle1.Format = "N2"; + dataGridViewCellStyle1.NullValue = null; + this.WarningThresholdColumn.DefaultCellStyle = dataGridViewCellStyle1; + this.WarningThresholdColumn.FillWeight = 98.27586F; + resources.ApplyResources(this.WarningThresholdColumn, "WarningThresholdColumn"); + this.WarningThresholdColumn.Name = "WarningThresholdColumn"; + // + // CriticalThresholdColumn + // + this.CriticalThresholdColumn.FillWeight = 98.27586F; + resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); + this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; + // + // NRPEEditPage + // + resources.ApplyResources(this, "$this"); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; + this.Controls.Add(this.NRPETableLayoutPanel); + this.Name = "NRPEEditPage"; + this.NRPETableLayoutPanel.ResumeLayout(false); + this.NRPETableLayoutPanel.PerformLayout(); + this.PoolTipsTableLayoutPanel.ResumeLayout(false); + this.PoolTipsTableLayoutPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PoolTipsPicture)).EndInit(); + this.GeneralConfigureGroupBox.ResumeLayout(false); + this.GeneralConfigTableLayoutPanel.ResumeLayout(false); + this.GeneralConfigTableLayoutPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + private TableLayoutPanel NRPETableLayoutPanel; + + private Label DescLabel; + + private GroupBox GeneralConfigureGroupBox; + private TableLayoutPanel GeneralConfigTableLayoutPanel; + + private CheckBox EnableNRPECheckBox; + private Label AllowHostsLabel; + private TextBox AllowHostsTextBox; + private CheckBox DebugLogCheckBox; + private CheckBox SslDebugLogCheckBox; + + private DataGridView CheckDataGridView; + private DataGridViewTextBoxColumn CheckColumn; + private DataGridViewTextBoxColumn WarningThresholdColumn; + private DataGridViewTextBoxColumn CriticalThresholdColumn; + + private TableLayoutPanel PoolTipsTableLayoutPanel; + private PictureBox PoolTipsPicture; + private Label PoolTipsLabel; + } +} \ No newline at end of file diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs new file mode 100644 index 0000000000..b33406a676 --- /dev/null +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -0,0 +1,397 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System; +using System.Drawing; +using System.Windows.Forms; +using XenAPI; +using XenAdmin.Actions; +using System.Collections.Generic; +using XenAdmin.Core; +using System.Text.RegularExpressions; + +namespace XenAdmin.SettingsPanels +{ + public partial class NRPEEditPage : UserControl, IEditPage + { + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + + private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); + private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); + private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); + + private readonly bool IsHost = true; + + private IXenObject Clone; + private readonly ToolTip InvalidParamToolTip; + private string InvalidParamToolTipText = ""; + + private readonly List CheckGroupList = new List(); + private readonly Dictionary CheckGroupDictByName = new Dictionary(); + private readonly Dictionary CheckGroupDictByLabel = new Dictionary(); + + private NRPEHostConfiguration NRPEOriginalConfig; + private NRPEHostConfiguration NRPECurrentConfig; + public string SubText + { + get + { + if (IsHost) + { + return EnableNRPECheckBox.Checked ? Messages.NRPE_ACTIVE : Messages.NRPE_INACTIVE; + } + else + { + return Messages.NRPE_BATCH_CONFIGURATION; + } + } + } + + public Image Image => Images.StaticImages._000_EnablePowerControl_h32bit_16; + + public NRPEEditPage(bool isHost) + { + IsHost = isHost; + InitializeComponent(); + Text = "NRPE"; + + NRPECurrentConfig = new NRPEHostConfiguration + { + EnableNRPE = false, + AllowHosts = NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER, + Debug = false, + SslLogging = false + }; + NRPEOriginalConfig = (NRPEHostConfiguration) NRPECurrentConfig.Clone(); + + EnableNRPECheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "enableNRPE"); + AllowHostsTextBox.DataBindings.Add("Text", NRPECurrentConfig, "allowHosts"); + DebugLogCheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "debug"); + SslDebugLogCheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "sslLogging"); + + CheckGroupList.Add(new HostLoadCheckGroup("check_host_load", Messages.NRPE_CHECK_HOST_LOAD)); + CheckGroupList.Add(new CheckGroup("check_host_cpu", Messages.NRPE_CHECK_HOST_CPU)); + CheckGroupList.Add(new CheckGroup("check_host_memory", Messages.NRPE_CHECK_HOST_MEMORY)); + CheckGroupList.Add(new CheckGroup("check_vgpu", Messages.NRPE_CHECK_VGPU)); + CheckGroupList.Add(new CheckGroup("check_vgpu_memory", Messages.NRPE_CHECK_VGPU_MEMORY)); + CheckGroupList.Add(new Dom0LoadCheckGroup("check_load", Messages.NRPE_CHECK_LOAD)); + CheckGroupList.Add(new CheckGroup("check_cpu", Messages.NRPE_CHECK_CPU)); + CheckGroupList.Add(new CheckGroup("check_memory", Messages.NRPE_CHECK_MEMORY)); + CheckGroupList.Add(new FreeCheckGroup("check_swap", Messages.NRPE_CHECK_SWAP)); + CheckGroupList.Add(new FreeCheckGroup("check_disk_root", Messages.NRPE_CHECK_DISK_ROOT)); + CheckGroupList.Add(new FreeCheckGroup("check_disk_log", Messages.NRPE_CHECK_DISK_LOG)); + + foreach (CheckGroup checkGroup in CheckGroupList) + { + CheckDataGridView.Rows.Add(checkGroup.CheckThresholdRow); + CheckGroupDictByName.Add(checkGroup.Name, checkGroup); + CheckGroupDictByLabel.Add(checkGroup.NameCell.Value.ToString(), checkGroup); + } + + UpdateOtherComponentBasedEnableNRPECheckBox(false); + + AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + AllowHostsTextBox.GotFocus += AllowHostsTextBox_GotFocus; + AllowHostsTextBox.LostFocus += AllowHostsTextBox_LostFocus; + + if (isHost) + { + PoolTipsPicture.Hide(); + PoolTipsLabel.Hide(); + } + InvalidParamToolTip = new ToolTip + { + IsBalloon = true, + ToolTipIcon = ToolTipIcon.Warning, + ToolTipTitle = Messages.INVALID_PARAMETER, + Tag = AllowHostsTextBox + }; + } + + public bool ValidToSave + { + get + { + InvalidParamToolTipText = ""; + InvalidParamToolTip.ToolTipTitle = ""; + CheckDataGridView.ShowCellToolTips = false; + + if (!EnableNRPECheckBox.Checked) + { + return true; + } + + bool valid = true; + if (!IsAllowHostsValid()) + { + valid = false; + } + + foreach (CheckGroup checkGroup in CheckGroupList) + { + if (!checkGroup.CheckValue()) + { + valid = false; + } + } + return valid; + } + } + + public bool HasChanged + { + get + { + return true; + } + } + + public void Cleanup() + { + } + + public void ShowLocalValidationMessages() + { + if (InvalidParamToolTip.Tag is Control ctrl) + { + InvalidParamToolTip.Hide(ctrl); + if (!InvalidParamToolTipText.Equals("")) + { + HelpersGUI.ShowBalloonMessage(ctrl, InvalidParamToolTip, InvalidParamToolTipText); + } + } + } + + public void HideLocalValidationMessages() + { + if (InvalidParamToolTip.Tag is Control ctrl && ctrl != null) + { + InvalidParamToolTip.Hide(ctrl); + } + } + + public void SetXenObjects(IXenObject orig, IXenObject clone) + { + Clone = clone; + if (IsHost) + { + InitNRPEGeneralConfiguration(); + InitNRPEThreshold(); + } + } + + public AsyncAction SaveSettings() + { + foreach (KeyValuePair item in CheckGroupDictByName) + { + if (item.Value.WarningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) + && item.Value.CriticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) + { + NRPECurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, + item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); + } + } + return new NRPEUpdateAction(Clone, NRPECurrentConfig, NRPEOriginalConfig, false); + } + + private void InitNRPEGeneralConfiguration() + { + string status = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_STATUS, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); + NRPECurrentConfig.EnableNRPE = status.Trim().Equals("active enabled"); + + string nrpeConfig = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); + + string[] nrpeConfigArray = nrpeConfig.Split('\n'); + foreach (string nrpeConfigItem in nrpeConfigArray) + { + if (nrpeConfigItem.Trim().StartsWith("allowed_hosts:")) + { + string allowHosts = nrpeConfigItem.Replace("allowed_hosts:", "").Trim(); + NRPECurrentConfig.AllowHosts = AllowHostsWithoutLocalAddress(allowHosts); + AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? + Color.FromKnownColor(KnownColor.ControlDark) : Color.FromKnownColor(KnownColor.ControlText); + } + else if (nrpeConfigItem.Trim().StartsWith("debug:")) + { + string enableDebug = nrpeConfigItem.Replace("debug:", "").Trim(); + NRPECurrentConfig.Debug = enableDebug.Equals(NRPEHostConfiguration.DEBUG_ENABLE); + } + else if (nrpeConfigItem.Trim().StartsWith("ssl_logging:")) + { + string enableSslLogging = nrpeConfigItem.Replace("ssl_logging:", "").Trim(); + NRPECurrentConfig.SslLogging = enableSslLogging.Equals(NRPEHostConfiguration.SSL_LOGGING_ENABLE); + } + } + NRPEOriginalConfig = (NRPEHostConfiguration) NRPECurrentConfig.Clone(); + + UpdateOtherComponentBasedEnableNRPECheckBox(EnableNRPECheckBox.Checked); + } + + private void InitNRPEThreshold() + { + string nrpeThreshold = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); + + string[] nrpeThresholdArray = nrpeThreshold.Split('\n'); + foreach (string nrpeThresholdItem in nrpeThresholdArray) + { + // Return string format for each line: check_cpu warning threshold - 50 critical threshold - 80 + string[] thresholdRtnArray = nrpeThresholdItem.Split(' '); + string checkName = thresholdRtnArray[0]; + if (CheckGroupDictByName.TryGetValue(thresholdRtnArray[0], out CheckGroup thresholdCheck)) + { + string warningThreshold = thresholdRtnArray[4]; + string criticalThreshold = thresholdRtnArray[8]; + thresholdCheck.UpdateThreshold(warningThreshold, criticalThreshold); + NRPEOriginalConfig.AddNRPECheck(new NRPEHostConfiguration.Check(checkName, warningThreshold, criticalThreshold)); + } + } + } + + private bool IsAllowHostsValid() + { + InvalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; + InvalidParamToolTip.Tag = AllowHostsTextBox; + CheckDataGridView.ShowCellToolTips = true; + + string str = AllowHostsTextBox.Text; + if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) + { + InvalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_EMPTY_ERROR; + return false; + } + + string[] hostArray = str.Split(','); + foreach (string host in hostArray) + { + if (!REGEX_IPV4.Match(host.Trim()).Success && + !REGEX_IPV4_CIDR.Match(host.Trim()).Success && + !REGEX_DOMAIN.Match(host.Trim()).Success) + { + InvalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; + return false; + } + } + CheckDataGridView.ShowCellToolTips = false; + return true; + } + + private string AllowHostsWithoutLocalAddress(string allowHosts) + { + string UpdatedAllowHosts = ""; + string[] AllowHostArray = allowHosts.Split(','); + foreach (string allowHost in AllowHostArray) + { + if (!allowHost.Trim().Equals("127.0.0.1") && + !allowHost.Trim().Equals("::1")) + { + UpdatedAllowHosts += allowHost + ","; + } + } + return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : + UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + } + + private void UpdateOtherComponentBasedEnableNRPECheckBox(bool check) + { + if (check) + { + AllowHostsTextBox.Enabled = true; + AllowHostsLabel.Enabled = true; + DebugLogCheckBox.Enabled = true; + SslDebugLogCheckBox.Enabled = true; + CheckDataGridView.Enabled = true; + CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Window); + CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Window); + } + else + { + AllowHostsTextBox.Enabled = false; + AllowHostsLabel.Enabled = false; + DebugLogCheckBox.Enabled = false; + SslDebugLogCheckBox.Enabled = false; + CheckDataGridView.Enabled = false; + CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Control); + CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Control); + } + } + + private void EnableNRPECheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateOtherComponentBasedEnableNRPECheckBox(EnableNRPECheckBox.Checked); + } + + private void AllowHostsTextBox_GotFocus(object sender, EventArgs e) + { + if (AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) + { + AllowHostsTextBox.Text = ""; + AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + } + + private void AllowHostsTextBox_LostFocus(object sender, EventArgs e) + { + if (string.IsNullOrWhiteSpace(AllowHostsTextBox.Text)) + { + AllowHostsTextBox.Text = NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER; + AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + } + } + + private void CheckDataGridView_BeginEdit(object sender, DataGridViewCellCancelEventArgs e) + { + DataGridViewCell currentCell = CheckDataGridView.CurrentRow.Cells[e.ColumnIndex]; + if (!IsHost && currentCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) + { + currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + currentCell.Value = ""; + } + } + + private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs e) + { + DataGridViewCell currentCell = CheckDataGridView.CurrentRow.Cells[e.ColumnIndex]; + if (!IsHost && currentCell.Value.ToString().Trim().Equals("")) + { + currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + CheckGroupDictByLabel.TryGetValue(CheckDataGridView.CurrentRow.Cells[0].Value.ToString(), out CheckGroup checkGroup); + currentCell.Value = currentCell.ColumnIndex == 1 ? + checkGroup.WarningThresholdDefault : (object)checkGroup.CriticalThresholdDefault; + } + } + } +} diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx new file mode 100644 index 0000000000..1359a1cf69 --- /dev/null +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -0,0 +1,615 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + Top, Left, Right + + + + True + + + 1 + + + Top, Left, Right + + + True + + + 2 + + + Left + + + + + + NoControl + + + + + + + 0, 7 + + + 0, 0, 0, 0 + + + 18, 17 + + + 17 + + + PoolTipsPicture + + + System.Windows.Forms.PictureBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PoolTipsTableLayoutPanel + + + 0 + + + Top, Bottom, Left, Right + + + True + + + NoControl + + + 23, 3 + + + 3, 3, 3, 3 + + + 600, 0 + + + 600, 26 + + + 16 + + + For the pool properties, there will not be showing the real configuration values in every host. When clicking OK, NRPE configuration and check threshold will be sent to all the hosts in this pool. + + + MiddleLeft + + + PoolTipsLabel + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PoolTipsTableLayoutPanel + + + 1 + + + 3, 407 + + + 1 + + + 641, 32 + + + 5 + + + PoolTipsTableLayoutPanel + + + System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 0 + + + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="PoolTipsPicture" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="PoolTipsLabel" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="Absolute,20,AutoSize,0" /><Rows Styles="Percent,100" /></TableLayoutSettings> + + + Top, Bottom, Left, Right + + + True + + + NoControl + + + 3, 0 + + + 641, 26 + + + 5 + + + NRPE (Nagios Remote Plugin Excutor) allow you to execute Nagios plugins on a remote host. You can modify NRPE general configuration and NRPE Check threshold in this page. + + + DescLabel + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 1 + + + Top, Bottom, Left, Right + + + Top, Bottom, Left, Right + + + 2 + + + Top, Left, Right + + + True + + + NoControl + + + 3, 3 + + + 636, 17 + + + 0 + + + Enable NRPE + + + EnableNRPECheckBox + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigTableLayoutPanel + + + 0 + + + NoControl + + + 3, 23 + + + 100, 24 + + + 1 + + + Allow Hosts: + + + MiddleLeft + + + AllowHostsLabel + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigTableLayoutPanel + + + 1 + + + Left, Right + + + 120, 25 + + + 3, 0, 20, 0 + + + 502, 20 + + + 2 + + + AllowHostsTextBox + + + System.Windows.Forms.TextBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigTableLayoutPanel + + + 2 + + + Top, Left, Right + + + True + + + NoControl + + + 3, 50 + + + 636, 17 + + + 3 + + + Record debugging message to syslog + + + DebugLogCheckBox + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigTableLayoutPanel + + + 3 + + + Top, Left, Right + + + True + + + NoControl + + + 3, 73 + + + 636, 17 + + + 4 + + + Record SSL message to syslog + + + SslDebugLogCheckBox + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigTableLayoutPanel + + + 4 + + + 10, 12 + + + 3, 3, 3, 0 + + + 6 + + + 642, 93 + + + 13 + + + GeneralConfigTableLayoutPanel + + + System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + GeneralConfigureGroupBox + + + 0 + + + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="EnableNRPECheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="AllowHostsLabel" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="2" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="4" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="Percent,18.36735,Percent,81.63265" /><Rows Styles="Absolute,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0" /></TableLayoutSettings> + + + 3, 29 + + + 3, 0, 3, 0 + + + 641, 118 + + + 7 + + + General Configuration + + + GeneralConfigureGroupBox + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 2 + + + Top, Left, Right + + + Check + + + 220 + + + True + + + Warning Threshold + + + 140 + + + True + + + Critical Threshold + + + 140 + + + 3, 153 + + + 641, 248 + + + 15 + + + CheckDataGridView + + + System.Windows.Forms.DataGridView, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 3 + + + 0, 0 + + + 3, 10, 3, 3 + + + 5 + + + 647, 442 + + + 4 + + + NRPETableLayoutPanel + + + System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 0 + + + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="PoolTipsTableLayoutPanel" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0" /></TableLayoutSettings> + + + True + + + 96, 96 + + + True + + + 650, 621 + + + CheckColumn + + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + WarningThresholdColumn + + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + CriticalThresholdColumn + + + System.Windows.Forms.DataGridViewTextBoxColumn, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPEEditPage + + + System.Windows.Forms.UserControl, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index f991310df6..5f26b3a417 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -477,6 +477,16 @@ NetworkOptionsEditPage.cs + + UserControl + + + NRPEEditPage.cs + + + NRPEEditPage.cs + UserControl + UserControl @@ -2104,6 +2114,10 @@ Designer HostPowerONEditPage.cs + + NRPEEditPage.cs + Designer + Designer PerfmonAlertOptionsPage.cs diff --git a/XenModel/Actions/Host/NRPEUpdateAction.cs b/XenModel/Actions/Host/NRPEUpdateAction.cs new file mode 100644 index 0000000000..38eefe94bf --- /dev/null +++ b/XenModel/Actions/Host/NRPEUpdateAction.cs @@ -0,0 +1,191 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System.Collections.Generic; +using System.Linq; +using XenAPI; + + +namespace XenAdmin.Actions +{ + public class NRPEUpdateAction : AsyncAction + { + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private readonly NRPEHostConfiguration NRPEOriginalConfig; // NRPE configuration fetched from host + private readonly NRPEHostConfiguration NRPEHostConfiguration; // NRPE configuration after user modified + + private readonly IXenObject Clone; + + public NRPEUpdateAction(IXenObject host, NRPEHostConfiguration nrpeHostConfiguration, NRPEHostConfiguration nrpeOriginalConfig, bool suppressHistory) + : base(host.Connection, Messages.ACTION_CHANGE_POWER_ON, Messages.NRPE_ACTION_CHANGING, suppressHistory) + { + Clone = host; + NRPEHostConfiguration = nrpeHostConfiguration; + NRPEOriginalConfig = nrpeOriginalConfig; + } + + protected override void Run() + { + if (Clone is Host) + { + SetNRPEConfigureForHost(); + } + else + { + SetNRPEConfigureForPool(); + } + } + + private void SetNRPEConfigureForHost() + { + // Enable/Disable NRPE + if (!NRPEHostConfiguration.EnableNRPE == NRPEOriginalConfig.EnableNRPE) + { + SetNRPEStatus(Clone, NRPEHostConfiguration.EnableNRPE); + } + if (!NRPEHostConfiguration.EnableNRPE) // If disable, return + { + return; + } + + // NRPE General Configuration + if (!NRPEHostConfiguration.AllowHosts.Equals(NRPEOriginalConfig.AllowHosts) + || !NRPEHostConfiguration.Debug.Equals(NRPEOriginalConfig.Debug) + || !NRPEHostConfiguration.SslLogging.Equals(NRPEOriginalConfig.SslLogging)) + { + SetNRPEGeneralConfiguration(Clone, NRPEHostConfiguration.AllowHosts, NRPEHostConfiguration.Debug, NRPEHostConfiguration.SslLogging); + } + + // NRPE Check Threshold + foreach (KeyValuePair kvp in NRPEHostConfiguration.CheckDict) + { + NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + NRPEOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); + if (CurrentCheck != null && OriginalCheck != null + && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) + || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) + { + SetNRPEThreshold(Clone, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); + } + } + + RestartNRPE(Clone); + } + + private void SetNRPEConfigureForPool() + { + List hostList = null; + if (Clone is Pool p) + { + hostList = p.Connection.Cache.Hosts.ToList(); + } + + hostList.ForEach(host => + { + // Enable/Disable NRPE + SetNRPEStatus(host, NRPEHostConfiguration.EnableNRPE); + if (!NRPEHostConfiguration.EnableNRPE) // If disable, return + { + return; + } + + // NRPE General Configuration + SetNRPEGeneralConfiguration(host, NRPEHostConfiguration.AllowHosts, NRPEHostConfiguration.Debug, NRPEHostConfiguration.SslLogging); + + // NRPE Check Threshold + foreach (KeyValuePair kvp in NRPEHostConfiguration.CheckDict) + { + NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + NRPEOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); + if (CurrentCheck != null) + { + SetNRPEThreshold(host, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); + } + } + + RestartNRPE(host); + }); + } + + private void SetNRPEStatus(IXenObject host, bool enableNRPE) + { + string nrpeUpdateStatusMethod = enableNRPE ? + NRPEHostConfiguration.XAPI_NRPE_ENABLE : NRPEHostConfiguration.XAPI_NRPE_DISABLE; + string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + nrpeUpdateStatusMethod, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", nrpeUpdateStatusMethod, result); + } + + private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, bool debug, bool sslLogging) + { + Dictionary ConfigArgDict = new Dictionary + { + { "allowed_hosts", "127.0.0.1,::1," + (allowHosts.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? "" : allowHosts) }, + { "debug", debug ? NRPEHostConfiguration.DEBUG_ENABLE : NRPEHostConfiguration.DEBUG_DISABLE }, + { "ssl_logging", sslLogging ? NRPEHostConfiguration.SSL_LOGGING_ENABLE : NRPEHostConfiguration.SSL_LOGGING_DISABLE} + }; + string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, ConfigArgDict); + log.InfoFormat("Execute nrpe {0}, allowed_hosts={1}, debug={2}, ssl_logging={3}, return: {4}", + NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, + NRPEHostConfiguration.AllowHosts, + NRPEHostConfiguration.Debug, + NRPEHostConfiguration.SslLogging, + result); + } + + private void SetNRPEThreshold(IXenObject host, string checkName, string warningThreshold, string criticalThreshold) + { + Dictionary ThresholdArgDict = new Dictionary + { + { checkName, null }, + { "w", warningThreshold }, + { "c", criticalThreshold } + }; + string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, ThresholdArgDict); + log.InfoFormat("Execute nrpe {0}, check={1}, w={2}, c={3}, return: {4}", + NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, + checkName, + warningThreshold, + criticalThreshold, + result); + } + + // After modified NRPE configuration, we need to restart NRPE to take effect + private void RestartNRPE(IXenObject host) + { + string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_RESTART, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_RESTART, result); + } + } +} diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 2d47ae38ce..4640a32aec 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29078,6 +29078,240 @@ public static string NOW { } } + /// + /// Looks up a localized string similar to Changing NRPE configuration.... + /// + public static string NRPE_ACTION_CHANGING { + get { + return ResourceManager.GetString("NRPE_ACTION_CHANGING", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NRPE service is active. + /// + public static string NRPE_ACTIVE { + get { + return ResourceManager.GetString("NRPE_ACTIVE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Allow hosts should not be empty.. + /// + public static string NRPE_ALLOW_HOSTS_EMPTY_ERROR { + get { + return ResourceManager.GetString("NRPE_ALLOW_HOSTS_EMPTY_ERROR", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Allow hosts format is not correct. + /// + public static string NRPE_ALLOW_HOSTS_ERROR_TITLE { + get { + return ResourceManager.GetString("NRPE_ALLOW_HOSTS_ERROR_TITLE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Allow hosts should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com. + /// + public static string NRPE_ALLOW_HOSTS_FORMAT_ERROR { + get { + return ResourceManager.GetString("NRPE_ALLOW_HOSTS_FORMAT_ERROR", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com. + /// + public static string NRPE_ALLOW_HOSTS_PLACE_HOLDER { + get { + return ResourceManager.GetString("NRPE_ALLOW_HOSTS_PLACE_HOLDER", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NRPE batch configuration. + /// + public static string NRPE_BATCH_CONFIGURATION { + get { + return ResourceManager.GetString("NRPE_BATCH_CONFIGURATION", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 CPU Usage (%). + /// + public static string NRPE_CHECK_CPU { + get { + return ResourceManager.GetString("NRPE_CHECK_CPU", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 Log Partition Free Space (%). + /// + public static string NRPE_CHECK_DISK_LOG { + get { + return ResourceManager.GetString("NRPE_CHECK_DISK_LOG", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 Root Partition Free Space (%). + /// + public static string NRPE_CHECK_DISK_ROOT { + get { + return ResourceManager.GetString("NRPE_CHECK_DISK_ROOT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Host CPU Usage (%). + /// + public static string NRPE_CHECK_HOST_CPU { + get { + return ResourceManager.GetString("NRPE_CHECK_HOST_CPU", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Host CPU Load. + /// + public static string NRPE_CHECK_HOST_LOAD { + get { + return ResourceManager.GetString("NRPE_CHECK_HOST_LOAD", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Host Memory Usage (%). + /// + public static string NRPE_CHECK_HOST_MEMORY { + get { + return ResourceManager.GetString("NRPE_CHECK_HOST_MEMORY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 CPU Load. + /// + public static string NRPE_CHECK_LOAD { + get { + return ResourceManager.GetString("NRPE_CHECK_LOAD", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 Memory Usage (%). + /// + public static string NRPE_CHECK_MEMORY { + get { + return ResourceManager.GetString("NRPE_CHECK_MEMORY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Dom0 Free Swap (%). + /// + public static string NRPE_CHECK_SWAP { + get { + return ResourceManager.GetString("NRPE_CHECK_SWAP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Host vGPU Memory Usage (%). + /// + public static string NRPE_CHECK_VGPU { + get { + return ResourceManager.GetString("NRPE_CHECK_VGPU", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Host vGPU Usage (%). + /// + public static string NRPE_CHECK_VGPU_MEMORY { + get { + return ResourceManager.GetString("NRPE_CHECK_VGPU_MEMORY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NRPE Configuration. + /// + public static string NRPE_EDIT_PAGE_TEXT { + get { + return ResourceManager.GetString("NRPE_EDIT_PAGE_TEXT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NRPE service is inactive. + /// + public static string NRPE_INACTIVE { + get { + return ResourceManager.GetString("NRPE_INACTIVE", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Threshold value should range from {0} to {1}.. + /// + public static string NRPE_THRESHOLD_RANGE_ERROR { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_RANGE_ERROR", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Threshold value should be 3 numbers separated with comma.. + /// + public static string NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Threshold value should be number.. + /// + public static string NRPE_THRESHOLD_SHOULD_BE_NUMBER { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_SHOULD_BE_NUMBER", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Threshold value should not be empty.. + /// + public static string NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Warning threshold should be bigger than critical threshold.. + /// + public static string NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Warning threshold should be less than critical threshold.. + /// + public static string NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL { + get { + return ResourceManager.GetString("NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL", resourceCulture); + } + } + /// /// Looks up a localized string similar to Number of snapshots to keep. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 2e4f0691d1..55095208a6 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10092,6 +10092,84 @@ When you configure an NFS storage repository, you simply provide the host name o Now + + Changing NRPE configuration... + + + NRPE service is active + + + Allow hosts should not be empty. + + + Allow hosts format is not correct + + + Allow hosts should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com + + + Comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com + + + NRPE batch configuration + + + Dom0 CPU Usage (%) + + + Dom0 Log Partition Free Space (%) + + + Dom0 Root Partition Free Space (%) + + + Host CPU Usage (%) + + + Host CPU Load + + + Host Memory Usage (%) + + + Dom0 CPU Load + + + Dom0 Memory Usage (%) + + + Dom0 Free Swap (%) + + + Host vGPU Memory Usage (%) + + + Host vGPU Usage (%) + + + NRPE Configuration + + + NRPE service is inactive + + + Threshold value should range from {0} to {1}. + + + Threshold value should be 3 numbers separated with comma. + + + Threshold value should be number. + + + Threshold value should not be empty. + + + Warning threshold should be bigger than critical threshold. + + + Warning threshold should be less than critical threshold. + Number of snapshots to keep diff --git a/XenModel/NRPE/NRPEHostConfiguration.cs b/XenModel/NRPE/NRPEHostConfiguration.cs new file mode 100644 index 0000000000..597556aacc --- /dev/null +++ b/XenModel/NRPE/NRPEHostConfiguration.cs @@ -0,0 +1,109 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; + +namespace XenAdmin +{ + public class NRPEHostConfiguration : ICloneable + { + public static readonly string XAPI_NRPE_PLUGIN_NAME = "nrpe"; + public static readonly string XAPI_NRPE_STATUS = "status"; + public static readonly string XAPI_NRPE_GET_CONFIG = "get-config"; + public static readonly string XAPI_NRPE_GET_THRESHOLD = "get-threshold"; + public static readonly string XAPI_NRPE_ENABLE = "enable"; + public static readonly string XAPI_NRPE_DISABLE = "disable"; + public static readonly string XAPI_NRPE_SET_CONFIG = "set-config"; + public static readonly string XAPI_NRPE_SET_THRESHOLD = "set-threshold"; + public static readonly string XAPI_NRPE_RESTART = "restart"; + + public static readonly string DEBUG_ENABLE = "1"; + public static readonly string DEBUG_DISABLE = "0"; + + public static readonly string SSL_LOGGING_ENABLE = "0xff"; + public static readonly string SSL_LOGGING_DISABLE = "0x00"; + + public static readonly string ALLOW_HOSTS_PLACE_HOLDER = Messages.NRPE_ALLOW_HOSTS_PLACE_HOLDER; + + private bool enableNRPE; + private string allowHosts; + private bool debug; + private bool sslLogging; + private readonly Dictionary checkDict = new Dictionary(); + + public bool EnableNRPE { get => enableNRPE; set => enableNRPE = value; } + public string AllowHosts { get => allowHosts; set => allowHosts = value; } + public bool Debug { get => debug; set => debug = value; } + public bool SslLogging { get => sslLogging; set => sslLogging = value; } + public Dictionary CheckDict { get => checkDict; } + + public class Check + { + public string Name; + public string WarningThreshold; + public string CriticalThreshold; + + public Check(string name, string warningThreshold, string criticalThreshold) + { + this.Name = name; + this.WarningThreshold = warningThreshold; + this.CriticalThreshold = criticalThreshold; + } + + } + + public NRPEHostConfiguration() + { + } + + public void AddNRPECheck(Check checkItem) + { + checkDict.Add(checkItem.Name, checkItem); + } + + public bool GetNRPECheck(string name, out Check check) + { + return checkDict.TryGetValue(name, out check); + } + + public object Clone() + { + NRPEHostConfiguration cloned = new NRPEHostConfiguration + { + enableNRPE = enableNRPE, + allowHosts = allowHosts, + debug = debug, + sslLogging = sslLogging + }; + return cloned; + } + } +} diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 13349a2b82..949403fbdf 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -88,6 +88,7 @@ + @@ -198,6 +199,7 @@ + From d941e0f5337365176e91dc0508e918b3eb122614 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 27 Sep 2023 13:01:46 +0100 Subject: [PATCH 03/31] Some layout and wording tweaks. Signed-off-by: Konstantina Chremmou --- .../SettingsPanels/NRPEEditPage.Designer.cs | 136 +++---- XenAdmin/SettingsPanels/NRPEEditPage.cs | 11 +- XenAdmin/SettingsPanels/NRPEEditPage.resx | 345 +++++++----------- XenAdmin/XenAdmin.csproj | 1 - 4 files changed, 192 insertions(+), 301 deletions(-) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index d5bcfdf005..5a157e6e75 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -1,6 +1,3 @@ -using System.Windows.Forms; -using DataGridView = System.Windows.Forms.DataGridView; - namespace XenAdmin.SettingsPanels { partial class NRPEEditPage @@ -32,26 +29,21 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NRPEEditPage)); - System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.NRPETableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.PoolTipsTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.PoolTipsPicture = new System.Windows.Forms.PictureBox(); - this.PoolTipsLabel = new System.Windows.Forms.Label(); - this.DescLabel = new System.Windows.Forms.Label(); + this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); + this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.descLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); this.GeneralConfigureGroupBox = new System.Windows.Forms.GroupBox(); this.GeneralConfigTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); this.AllowHostsLabel = new System.Windows.Forms.Label(); this.AllowHostsTextBox = new System.Windows.Forms.TextBox(); this.DebugLogCheckBox = new System.Windows.Forms.CheckBox(); this.SslDebugLogCheckBox = new System.Windows.Forms.CheckBox(); - this.CheckDataGridView = new System.Windows.Forms.DataGridView(); + this.CheckDataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NRPETableLayoutPanel.SuspendLayout(); - this.PoolTipsTableLayoutPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.PoolTipsPicture)).BeginInit(); this.GeneralConfigureGroupBox.SuspendLayout(); this.GeneralConfigTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); @@ -60,61 +52,46 @@ private void InitializeComponent() // NRPETableLayoutPanel // resources.ApplyResources(this.NRPETableLayoutPanel, "NRPETableLayoutPanel"); - this.NRPETableLayoutPanel.Controls.Add(this.PoolTipsTableLayoutPanel, 0, 4); - this.NRPETableLayoutPanel.Controls.Add(this.DescLabel, 0, 0); - this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 1); - this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 2); + this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 2); + this.NRPETableLayoutPanel.Controls.Add(this.DescLabelPool, 0, 0); + this.NRPETableLayoutPanel.Controls.Add(this.descLabelHost, 0, 1); + this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 3); + this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 4); this.NRPETableLayoutPanel.Name = "NRPETableLayoutPanel"; // - // PoolTipsTableLayoutPanel - // - resources.ApplyResources(this.PoolTipsTableLayoutPanel, "PoolTipsTableLayoutPanel"); - this.PoolTipsTableLayoutPanel.Controls.Add(this.PoolTipsPicture, 0, 0); - this.PoolTipsTableLayoutPanel.Controls.Add(this.PoolTipsLabel, 1, 0); - this.PoolTipsTableLayoutPanel.Name = "PoolTipsTableLayoutPanel"; - // - // PoolTipsPicture + // EnableNRPECheckBox // - resources.ApplyResources(this.PoolTipsPicture, "PoolTipsPicture"); - this.PoolTipsPicture.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16; - this.PoolTipsPicture.Name = "PoolTipsPicture"; - this.PoolTipsPicture.TabStop = false; + resources.ApplyResources(this.EnableNRPECheckBox, "EnableNRPECheckBox"); + this.EnableNRPECheckBox.Name = "EnableNRPECheckBox"; + this.EnableNRPECheckBox.UseVisualStyleBackColor = true; + this.EnableNRPECheckBox.CheckedChanged += new System.EventHandler(this.EnableNRPECheckBox_CheckedChanged); // - // PoolTipsLabel + // DescLabelPool // - resources.ApplyResources(this.PoolTipsLabel, "PoolTipsLabel"); - this.PoolTipsLabel.Name = "PoolTipsLabel"; + resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); + this.DescLabelPool.Name = "DescLabelPool"; // - // DescLabel + // descLabelHost // - resources.ApplyResources(this.DescLabel, "DescLabel"); - this.DescLabel.Name = "DescLabel"; + resources.ApplyResources(this.descLabelHost, "descLabelHost"); + this.descLabelHost.Name = "descLabelHost"; // // GeneralConfigureGroupBox // - resources.ApplyResources(this.GeneralConfigureGroupBox, "GeneralConfigureGroupBox"); this.GeneralConfigureGroupBox.Controls.Add(this.GeneralConfigTableLayoutPanel); + resources.ApplyResources(this.GeneralConfigureGroupBox, "GeneralConfigureGroupBox"); this.GeneralConfigureGroupBox.Name = "GeneralConfigureGroupBox"; this.GeneralConfigureGroupBox.TabStop = false; // // GeneralConfigTableLayoutPanel // resources.ApplyResources(this.GeneralConfigTableLayoutPanel, "GeneralConfigTableLayoutPanel"); - this.GeneralConfigTableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 1); - this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsLabel, 0, 2); - this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsTextBox, 1, 2); - this.GeneralConfigTableLayoutPanel.Controls.Add(this.DebugLogCheckBox, 0, 3); - this.GeneralConfigTableLayoutPanel.Controls.Add(this.SslDebugLogCheckBox, 0, 4); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsLabel, 0, 0); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.AllowHostsTextBox, 1, 0); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.DebugLogCheckBox, 0, 1); + this.GeneralConfigTableLayoutPanel.Controls.Add(this.SslDebugLogCheckBox, 0, 2); this.GeneralConfigTableLayoutPanel.Name = "GeneralConfigTableLayoutPanel"; // - // EnableNRPECheckBox - // - resources.ApplyResources(this.EnableNRPECheckBox, "EnableNRPECheckBox"); - this.GeneralConfigTableLayoutPanel.SetColumnSpan(this.EnableNRPECheckBox, 2); - this.EnableNRPECheckBox.Name = "EnableNRPECheckBox"; - this.EnableNRPECheckBox.UseVisualStyleBackColor = true; - this.EnableNRPECheckBox.CheckedChanged += new System.EventHandler(this.EnableNRPECheckBox_CheckedChanged); - // // AllowHostsLabel // resources.ApplyResources(this.AllowHostsLabel, "AllowHostsLabel"); @@ -141,45 +118,37 @@ private void InitializeComponent() // // CheckDataGridView // - this.CheckDataGridView.AllowUserToAddRows = false; - this.CheckDataGridView.AllowUserToDeleteRows = false; - this.CheckDataGridView.AllowUserToResizeRows = false; - resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); - this.CheckDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; - this.CheckDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.CheckDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; + this.CheckDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + this.CheckDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.CheckColumn, this.WarningThresholdColumn, this.CriticalThresholdColumn}); + resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; - this.CheckDataGridView.EnableHeadersVisualStyles = false; - this.CheckDataGridView.MultiSelect = false; this.CheckDataGridView.Name = "CheckDataGridView"; - this.CheckDataGridView.RowHeadersVisible = false; + this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; + this.CheckDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; this.CheckDataGridView.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.CheckDataGridView_BeginEdit); this.CheckDataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.CheckDataGridView_EndEdit); // // CheckColumn // - this.CheckColumn.FillWeight = 103.4483F; + this.CheckColumn.FillWeight = 40F; resources.ApplyResources(this.CheckColumn, "CheckColumn"); this.CheckColumn.Name = "CheckColumn"; this.CheckColumn.ReadOnly = true; // // WarningThresholdColumn // - dataGridViewCellStyle1.Format = "N2"; - dataGridViewCellStyle1.NullValue = null; - this.WarningThresholdColumn.DefaultCellStyle = dataGridViewCellStyle1; - this.WarningThresholdColumn.FillWeight = 98.27586F; + this.WarningThresholdColumn.FillWeight = 30F; resources.ApplyResources(this.WarningThresholdColumn, "WarningThresholdColumn"); this.WarningThresholdColumn.Name = "WarningThresholdColumn"; // // CriticalThresholdColumn // - this.CriticalThresholdColumn.FillWeight = 98.27586F; + this.CriticalThresholdColumn.FillWeight = 30F; resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; // @@ -191,10 +160,8 @@ private void InitializeComponent() this.Name = "NRPEEditPage"; this.NRPETableLayoutPanel.ResumeLayout(false); this.NRPETableLayoutPanel.PerformLayout(); - this.PoolTipsTableLayoutPanel.ResumeLayout(false); - this.PoolTipsTableLayoutPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.PoolTipsPicture)).EndInit(); this.GeneralConfigureGroupBox.ResumeLayout(false); + this.GeneralConfigureGroupBox.PerformLayout(); this.GeneralConfigTableLayoutPanel.ResumeLayout(false); this.GeneralConfigTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); @@ -204,26 +171,19 @@ private void InitializeComponent() } #endregion - private TableLayoutPanel NRPETableLayoutPanel; - - private Label DescLabel; - - private GroupBox GeneralConfigureGroupBox; - private TableLayoutPanel GeneralConfigTableLayoutPanel; - - private CheckBox EnableNRPECheckBox; - private Label AllowHostsLabel; - private TextBox AllowHostsTextBox; - private CheckBox DebugLogCheckBox; - private CheckBox SslDebugLogCheckBox; - - private DataGridView CheckDataGridView; - private DataGridViewTextBoxColumn CheckColumn; - private DataGridViewTextBoxColumn WarningThresholdColumn; - private DataGridViewTextBoxColumn CriticalThresholdColumn; - - private TableLayoutPanel PoolTipsTableLayoutPanel; - private PictureBox PoolTipsPicture; - private Label PoolTipsLabel; + private System.Windows.Forms.TableLayoutPanel NRPETableLayoutPanel; + private XenAdmin.Controls.Common.AutoHeightLabel DescLabelPool; + private System.Windows.Forms.GroupBox GeneralConfigureGroupBox; + private System.Windows.Forms.TableLayoutPanel GeneralConfigTableLayoutPanel; + private System.Windows.Forms.CheckBox EnableNRPECheckBox; + private System.Windows.Forms.Label AllowHostsLabel; + private System.Windows.Forms.TextBox AllowHostsTextBox; + private System.Windows.Forms.CheckBox DebugLogCheckBox; + private System.Windows.Forms.CheckBox SslDebugLogCheckBox; + private Controls.DataGridViewEx.DataGridViewEx CheckDataGridView; + private Controls.Common.AutoHeightLabel descLabelHost; + private System.Windows.Forms.DataGridViewTextBoxColumn CheckColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn WarningThresholdColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn CriticalThresholdColumn; } } \ No newline at end of file diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index b33406a676..eae55f6b1c 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -75,7 +75,7 @@ public string SubText } } - public Image Image => Images.StaticImages._000_EnablePowerControl_h32bit_16; + public Image Image => Images.StaticImages._000_Module_h32bit_16; public NRPEEditPage(bool isHost) { @@ -122,11 +122,6 @@ public NRPEEditPage(bool isHost) AllowHostsTextBox.GotFocus += AllowHostsTextBox_GotFocus; AllowHostsTextBox.LostFocus += AllowHostsTextBox_LostFocus; - if (isHost) - { - PoolTipsPicture.Hide(); - PoolTipsLabel.Hide(); - } InvalidParamToolTip = new ToolTip { IsBalloon = true, @@ -201,6 +196,10 @@ public void HideLocalValidationMessages() public void SetXenObjects(IXenObject orig, IXenObject clone) { Clone = clone; + + descLabelHost.Visible = IsHost; + DescLabelPool.Visible = !IsHost; + if (IsHost) { InitNRPEGeneralConfiguration(); diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx index 1359a1cf69..434ae82164 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.resx +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -117,10 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Top, Left, Right - True @@ -128,213 +124,144 @@ 1 - - Top, Left, Right - - + True - - 2 - - - Left - - - - - + + NoControl - - - - - 0, 7 - - - 0, 0, 0, 0 - - - 18, 17 - - - 17 - - - PoolTipsPicture - - - System.Windows.Forms.PictureBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - PoolTipsTableLayoutPanel - - - 0 - - - Top, Bottom, Left, Right + + 3, 88 - - True + + 3, 3, 3, 8 - - NoControl + + 3, 0, 0, 0 - - 23, 3 + + 95, 17 - - 3, 3, 3, 3 + + 2 - - 600, 0 + + &Enable NRPE - - 600, 26 + + EnableNRPECheckBox - - 16 + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - For the pool properties, there will not be showing the real configuration values in every host. When clicking OK, NRPE configuration and check threshold will be sent to all the hosts in this pool. + + NRPETableLayoutPanel - - MiddleLeft + + 0 - - PoolTipsLabel + + True - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Fill - - PoolTipsTableLayoutPanel + + NoControl - - 1 + + 3, 0 - - 3, 407 + + 3, 0, 3, 10 - - 1 + + 644, 39 - - 641, 32 + + 0 - - 5 + + Nagios Remote Plugin Executor (NRPE) allows you to monitor remotely resource metrics on the servers of your pool. +This page does not offer an overview of the NRPE configuration and metric threshold settings of the pool servers. Use it only to apply your chosen configuration and threshold settings to all servers in the pool. - - PoolTipsTableLayoutPanel + + DescLabelPool - - System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - + NRPETableLayoutPanel - - 0 - - - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="PoolTipsPicture" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="PoolTipsLabel" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="Absolute,20,AutoSize,0" /><Rows Styles="Percent,100" /></TableLayoutSettings> - - - Top, Bottom, Left, Right + + 1 - + True - - NoControl + + Fill - - 3, 0 + + 3, 49 - - 641, 26 + + 3, 0, 3, 10 - - 5 + + 644, 26 - - NRPE (Nagios Remote Plugin Excutor) allow you to execute Nagios plugins on a remote host. You can modify NRPE general configuration and NRPE Check threshold in this page. + + 1 - - DescLabel + + Nagios Remote Plugin Executor (NRPE) allows you to monitor remotely resource metrics on the servers of your pool. +Use this page to review and modify the NRPE configuration and metric threshold settings used for this server. - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + descLabelHost - + + XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + + NRPETableLayoutPanel - - 1 + + 2 - - Top, Bottom, Left, Right + + True - - Top, Bottom, Left, Right + + GrowAndShrink 2 - - Top, Left, Right + + Left - + True - - NoControl - - - 3, 3 - - - 636, 17 - - - 0 - - - Enable NRPE - - - EnableNRPECheckBox - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - GeneralConfigTableLayoutPanel - - - 0 - NoControl - 3, 23 + 3, 6 - 100, 24 + 96, 13 - 1 + 0 - Allow Hosts: - - - MiddleLeft + &Monitoring servers: AllowHostsLabel @@ -346,22 +273,19 @@ GeneralConfigTableLayoutPanel - 1 + 0 Left, Right - 120, 25 - - - 3, 0, 20, 0 + 105, 3 - 502, 20 + 530, 20 - 2 + 1 AllowHostsTextBox @@ -373,10 +297,7 @@ GeneralConfigTableLayoutPanel - 2 - - - Top, Left, Right + 1 True @@ -385,16 +306,19 @@ NoControl - 3, 50 + 3, 29 + + + 3, 0, 0, 0 - 636, 17 + 211, 17 - 3 + 2 - Record debugging message to syslog + Record &debugging messages to syslog DebugLogCheckBox @@ -406,10 +330,7 @@ GeneralConfigTableLayoutPanel - 3 - - - Top, Left, Right + 2 True @@ -418,16 +339,19 @@ NoControl - 3, 73 + 3, 52 + + + 3, 0, 0, 0 - 636, 17 + 181, 17 - 4 + 3 - Record SSL message to syslog + Record &SSL messages to syslog SslDebugLogCheckBox @@ -439,22 +363,22 @@ GeneralConfigTableLayoutPanel - 4 + 3 - - 10, 12 + + Top - - 3, 3, 3, 0 + + 3, 16 - 6 + 3 - 642, 93 + 638, 72 - 13 + 0 GeneralConfigTableLayoutPanel @@ -469,19 +393,25 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="EnableNRPECheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="AllowHostsLabel" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="2" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="4" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="Percent,18.36735,Percent,81.63265" /><Rows Styles="Absolute,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,20" /></TableLayoutSettings> + + + Fill - 3, 29 + 3, 116 + + + 3, 3, 3, 10 - 3, 0, 3, 0 + 3, 3, 3, 0 - 641, 118 + 644, 100 - 7 + 3 General Configuration @@ -496,16 +426,13 @@ NRPETableLayoutPanel - 2 - - - Top, Left, Right + 3 - Check + Metric - 220 + 100 True @@ -514,7 +441,7 @@ Warning Threshold - 140 + 100 True @@ -523,28 +450,34 @@ Critical Threshold - 140 + 100 + + + Fill - 3, 153 + 3, 229 - 641, 248 + 644, 305 - 15 + 4 CheckDataGridView - System.Windows.Forms.DataGridView, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + XenAdmin.Controls.DataGridViewEx.DataGridViewEx, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel - 3 + 4 + + + Fill 0, 0 @@ -556,10 +489,10 @@ 5 - 647, 442 + 650, 537 - 4 + 0 NRPETableLayoutPanel @@ -574,7 +507,7 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="PoolTipsTableLayoutPanel" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="EnableNRPECheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="descLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100" /></TableLayoutSettings> True @@ -586,7 +519,7 @@ True - 650, 621 + 650, 537 CheckColumn diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index 5f26b3a417..11b51bdb1f 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -484,7 +484,6 @@ NRPEEditPage.cs - NRPEEditPage.cs UserControl From a20ea5ab6e691a984be8830e7b1d6ffb0a0acb39 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 27 Sep 2023 19:05:27 +0100 Subject: [PATCH 04/31] Moved NRPE related files to the same folder. Signed-off-by: Konstantina Chremmou --- XenAdmin/SettingsPanels/NRPEEditPage.cs | 8 +++++--- XenModel/{ => Actions}/NRPE/NRPEHostConfiguration.cs | 2 +- XenModel/Actions/{Host => NRPE}/NRPEUpdateAction.cs | 2 +- XenModel/XenModel.csproj | 4 ++-- 4 files changed, 9 insertions(+), 7 deletions(-) rename XenModel/{ => Actions}/NRPE/NRPEHostConfiguration.cs (96%) rename XenModel/Actions/{Host => NRPE}/NRPEUpdateAction.cs (97%) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index eae55f6b1c..d89080012d 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -29,13 +29,15 @@ */ using System; +using System.Collections.Generic; using System.Drawing; +using System.Text.RegularExpressions; using System.Windows.Forms; -using XenAPI; using XenAdmin.Actions; -using System.Collections.Generic; using XenAdmin.Core; -using System.Text.RegularExpressions; +using XenAdmin.Actions.NRPE; +using XenAPI; + namespace XenAdmin.SettingsPanels { diff --git a/XenModel/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs similarity index 96% rename from XenModel/NRPE/NRPEHostConfiguration.cs rename to XenModel/Actions/NRPE/NRPEHostConfiguration.cs index 597556aacc..c143a3cca6 100644 --- a/XenModel/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -31,7 +31,7 @@ using System; using System.Collections.Generic; -namespace XenAdmin +namespace XenAdmin.Actions.NRPE { public class NRPEHostConfiguration : ICloneable { diff --git a/XenModel/Actions/Host/NRPEUpdateAction.cs b/XenModel/Actions/NRPE/NRPEUpdateAction.cs similarity index 97% rename from XenModel/Actions/Host/NRPEUpdateAction.cs rename to XenModel/Actions/NRPE/NRPEUpdateAction.cs index 38eefe94bf..05cb749dbe 100644 --- a/XenModel/Actions/Host/NRPEUpdateAction.cs +++ b/XenModel/Actions/NRPE/NRPEUpdateAction.cs @@ -33,7 +33,7 @@ using XenAPI; -namespace XenAdmin.Actions +namespace XenAdmin.Actions.NRPE { public class NRPEUpdateAction : AsyncAction { diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 949403fbdf..2850c5ca4d 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -88,7 +88,7 @@ - + @@ -199,7 +199,7 @@ - + From 794e1f3fbdb85bf8f79f1408a2b10d7b52d35478 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Thu, 28 Sep 2023 13:22:46 +0100 Subject: [PATCH 05/31] Some corrections in wording, code style, C# usage, and null checks. Signed-off-by: Konstantina Chremmou --- XenAdmin/Dialogs/PropertiesDialog.cs | 2 +- XenAdmin/SettingsPanels/NRPEEditPage.cs | 66 +++++++++-------- .../Actions/NRPE/NRPEHostConfiguration.cs | 72 +++++++++---------- XenModel/Messages.Designer.cs | 21 ++++-- XenModel/Messages.resx | 15 ++-- 5 files changed, 91 insertions(+), 85 deletions(-) diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index a6dda37d70..b35caaf895 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -320,7 +320,7 @@ private void Build() } if (isHost || isPool) { - NRPEEditPage = new NRPEEditPage(isHost); + NRPEEditPage = new NRPEEditPage(); ShowTab(NRPEEditPage); } } diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index d89080012d..ccf22e2e3a 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -45,12 +45,11 @@ public partial class NRPEEditPage : UserControl, IEditPage { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); - private readonly bool IsHost = true; + private bool _isHost; private IXenObject Clone; private readonly ToolTip InvalidParamToolTip; @@ -62,11 +61,12 @@ public partial class NRPEEditPage : UserControl, IEditPage private NRPEHostConfiguration NRPEOriginalConfig; private NRPEHostConfiguration NRPECurrentConfig; + public string SubText { get { - if (IsHost) + if (_isHost) { return EnableNRPECheckBox.Checked ? Messages.NRPE_ACTIVE : Messages.NRPE_INACTIVE; } @@ -79,11 +79,10 @@ public string SubText public Image Image => Images.StaticImages._000_Module_h32bit_16; - public NRPEEditPage(bool isHost) + public NRPEEditPage() { - IsHost = isHost; InitializeComponent(); - Text = "NRPE"; + Text = Messages.NRPE; NRPECurrentConfig = new NRPEHostConfiguration { @@ -118,7 +117,7 @@ public NRPEEditPage(bool isHost) CheckGroupDictByLabel.Add(checkGroup.NameCell.Value.ToString(), checkGroup); } - UpdateOtherComponentBasedEnableNRPECheckBox(false); + UpdateOtherComponentBasedEnableNRPECheckBox(); AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); AllowHostsTextBox.GotFocus += AllowHostsTextBox_GotFocus; @@ -146,11 +145,7 @@ public bool ValidToSave return true; } - bool valid = true; - if (!IsAllowHostsValid()) - { - valid = false; - } + bool valid = IsAllowHostsValid(); foreach (CheckGroup checkGroup in CheckGroupList) { @@ -189,7 +184,7 @@ public void ShowLocalValidationMessages() public void HideLocalValidationMessages() { - if (InvalidParamToolTip.Tag is Control ctrl && ctrl != null) + if (InvalidParamToolTip.Tag is Control ctrl) { InvalidParamToolTip.Hide(ctrl); } @@ -198,11 +193,12 @@ public void HideLocalValidationMessages() public void SetXenObjects(IXenObject orig, IXenObject clone) { Clone = clone; + _isHost = Clone is Host; - descLabelHost.Visible = IsHost; - DescLabelPool.Visible = !IsHost; + descLabelHost.Visible = _isHost; + DescLabelPool.Visible = !_isHost; - if (IsHost) + if (_isHost) { InitNRPEGeneralConfiguration(); InitNRPEThreshold(); @@ -257,7 +253,7 @@ private void InitNRPEGeneralConfiguration() } NRPEOriginalConfig = (NRPEHostConfiguration) NRPECurrentConfig.Clone(); - UpdateOtherComponentBasedEnableNRPECheckBox(EnableNRPECheckBox.Checked); + UpdateOtherComponentBasedEnableNRPECheckBox(); } private void InitNRPEThreshold() @@ -326,24 +322,18 @@ private string AllowHostsWithoutLocalAddress(string allowHosts) UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); } - private void UpdateOtherComponentBasedEnableNRPECheckBox(bool check) + private void UpdateOtherComponentBasedEnableNRPECheckBox() { - if (check) + if (EnableNRPECheckBox.Checked) { - AllowHostsTextBox.Enabled = true; - AllowHostsLabel.Enabled = true; - DebugLogCheckBox.Enabled = true; - SslDebugLogCheckBox.Enabled = true; + GeneralConfigureGroupBox.Enabled = true; CheckDataGridView.Enabled = true; CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Window); CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Window); } else { - AllowHostsTextBox.Enabled = false; - AllowHostsLabel.Enabled = false; - DebugLogCheckBox.Enabled = false; - SslDebugLogCheckBox.Enabled = false; + GeneralConfigureGroupBox.Enabled = false; CheckDataGridView.Enabled = false; CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Control); CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Control); @@ -352,7 +342,7 @@ private void UpdateOtherComponentBasedEnableNRPECheckBox(bool check) private void EnableNRPECheckBox_CheckedChanged(object sender, EventArgs e) { - UpdateOtherComponentBasedEnableNRPECheckBox(EnableNRPECheckBox.Checked); + UpdateOtherComponentBasedEnableNRPECheckBox(); } private void AllowHostsTextBox_GotFocus(object sender, EventArgs e) @@ -375,8 +365,9 @@ private void AllowHostsTextBox_LostFocus(object sender, EventArgs e) private void CheckDataGridView_BeginEdit(object sender, DataGridViewCellCancelEventArgs e) { - DataGridViewCell currentCell = CheckDataGridView.CurrentRow.Cells[e.ColumnIndex]; - if (!IsHost && currentCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) + DataGridViewCell currentCell = CheckDataGridView.CurrentRow?.Cells[e.ColumnIndex]; + + if (currentCell != null && !_isHost && currentCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) { currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); currentCell.Value = ""; @@ -385,13 +376,20 @@ private void CheckDataGridView_BeginEdit(object sender, DataGridViewCellCancelEv private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs e) { - DataGridViewCell currentCell = CheckDataGridView.CurrentRow.Cells[e.ColumnIndex]; - if (!IsHost && currentCell.Value.ToString().Trim().Equals("")) + DataGridViewCell currentCell = CheckDataGridView.CurrentRow?.Cells[e.ColumnIndex]; + + if (currentCell != null &&!_isHost && currentCell.Value.ToString().Trim().Equals("")) { currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); CheckGroupDictByLabel.TryGetValue(CheckDataGridView.CurrentRow.Cells[0].Value.ToString(), out CheckGroup checkGroup); - currentCell.Value = currentCell.ColumnIndex == 1 ? - checkGroup.WarningThresholdDefault : (object)checkGroup.CriticalThresholdDefault; + + if (checkGroup != null) + { + if (currentCell.ColumnIndex == WarningThresholdColumn.Index) + currentCell.Value = checkGroup.WarningThresholdDefault; + else if (currentCell.ColumnIndex == CriticalThresholdColumn.Index) + currentCell.Value = checkGroup.CriticalThresholdDefault; + } } } } diff --git a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs index c143a3cca6..7f1e62098f 100644 --- a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -35,55 +35,51 @@ namespace XenAdmin.Actions.NRPE { public class NRPEHostConfiguration : ICloneable { - public static readonly string XAPI_NRPE_PLUGIN_NAME = "nrpe"; - public static readonly string XAPI_NRPE_STATUS = "status"; - public static readonly string XAPI_NRPE_GET_CONFIG = "get-config"; - public static readonly string XAPI_NRPE_GET_THRESHOLD = "get-threshold"; - public static readonly string XAPI_NRPE_ENABLE = "enable"; - public static readonly string XAPI_NRPE_DISABLE = "disable"; - public static readonly string XAPI_NRPE_SET_CONFIG = "set-config"; - public static readonly string XAPI_NRPE_SET_THRESHOLD = "set-threshold"; - public static readonly string XAPI_NRPE_RESTART = "restart"; - - public static readonly string DEBUG_ENABLE = "1"; - public static readonly string DEBUG_DISABLE = "0"; - - public static readonly string SSL_LOGGING_ENABLE = "0xff"; - public static readonly string SSL_LOGGING_DISABLE = "0x00"; + public const string XAPI_NRPE_PLUGIN_NAME = "nrpe"; + public const string XAPI_NRPE_STATUS = "status"; + public const string XAPI_NRPE_GET_CONFIG = "get-config"; + public const string XAPI_NRPE_GET_THRESHOLD = "get-threshold"; + public const string XAPI_NRPE_ENABLE = "enable"; + public const string XAPI_NRPE_DISABLE = "disable"; + public const string XAPI_NRPE_SET_CONFIG = "set-config"; + public const string XAPI_NRPE_SET_THRESHOLD = "set-threshold"; + public const string XAPI_NRPE_RESTART = "restart"; + + public const string DEBUG_ENABLE = "1"; + public const string DEBUG_DISABLE = "0"; + + public const string SSL_LOGGING_ENABLE = "0xff"; + public const string SSL_LOGGING_DISABLE = "0x00"; public static readonly string ALLOW_HOSTS_PLACE_HOLDER = Messages.NRPE_ALLOW_HOSTS_PLACE_HOLDER; - private bool enableNRPE; - private string allowHosts; - private bool debug; - private bool sslLogging; private readonly Dictionary checkDict = new Dictionary(); - public bool EnableNRPE { get => enableNRPE; set => enableNRPE = value; } - public string AllowHosts { get => allowHosts; set => allowHosts = value; } - public bool Debug { get => debug; set => debug = value; } - public bool SslLogging { get => sslLogging; set => sslLogging = value; } - public Dictionary CheckDict { get => checkDict; } + public bool EnableNRPE { get; set; } + + public string AllowHosts { get; set; } + + public bool Debug { get; set; } + + public bool SslLogging { get; set; } + + public Dictionary CheckDict => checkDict; public class Check { - public string Name; - public string WarningThreshold; - public string CriticalThreshold; + public string Name { get; } + public string WarningThreshold { get; } + public string CriticalThreshold{ get; } public Check(string name, string warningThreshold, string criticalThreshold) { - this.Name = name; - this.WarningThreshold = warningThreshold; - this.CriticalThreshold = criticalThreshold; + Name = name; + WarningThreshold = warningThreshold; + CriticalThreshold = criticalThreshold; } } - public NRPEHostConfiguration() - { - } - public void AddNRPECheck(Check checkItem) { checkDict.Add(checkItem.Name, checkItem); @@ -98,10 +94,10 @@ public object Clone() { NRPEHostConfiguration cloned = new NRPEHostConfiguration { - enableNRPE = enableNRPE, - allowHosts = allowHosts, - debug = debug, - sslLogging = sslLogging + EnableNRPE = EnableNRPE, + AllowHosts = AllowHosts, + Debug = Debug, + SslLogging = SslLogging }; return cloned; } diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 4640a32aec..e387c153d0 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29078,6 +29078,15 @@ public static string NOW { } } + /// + /// Looks up a localized string similar to NRPE. + /// + public static string NRPE { + get { + return ResourceManager.GetString("NRPE", resourceCulture); + } + } + /// /// Looks up a localized string similar to Changing NRPE configuration.... /// @@ -29097,7 +29106,7 @@ public static string NRPE_ACTIVE { } /// - /// Looks up a localized string similar to Allow hosts should not be empty.. + /// Looks up a localized string similar to Monitoring servers should not be empty.. /// public static string NRPE_ALLOW_HOSTS_EMPTY_ERROR { get { @@ -29106,7 +29115,7 @@ public static string NRPE_ALLOW_HOSTS_EMPTY_ERROR { } /// - /// Looks up a localized string similar to Allow hosts format is not correct. + /// Looks up a localized string similar to Monitoring servers format is not correct. /// public static string NRPE_ALLOW_HOSTS_ERROR_TITLE { get { @@ -29115,7 +29124,7 @@ public static string NRPE_ALLOW_HOSTS_ERROR_TITLE { } /// - /// Looks up a localized string similar to Allow hosts should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com. + /// Looks up a localized string similar to Monitoring servers should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com. /// public static string NRPE_ALLOW_HOSTS_FORMAT_ERROR { get { @@ -29268,7 +29277,7 @@ public static string NRPE_THRESHOLD_RANGE_ERROR { } /// - /// Looks up a localized string similar to Threshold value should be 3 numbers separated with comma.. + /// Looks up a localized string similar to Threshold value should consist of 3 comma separated numbers.. /// public static string NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS { get { @@ -29277,7 +29286,7 @@ public static string NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS { } /// - /// Looks up a localized string similar to Threshold value should be number.. + /// Looks up a localized string similar to Threshold value should be a number.. /// public static string NRPE_THRESHOLD_SHOULD_BE_NUMBER { get { @@ -29295,7 +29304,7 @@ public static string NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY { } /// - /// Looks up a localized string similar to Warning threshold should be bigger than critical threshold.. + /// Looks up a localized string similar to Warning threshold should be greater than critical threshold.. /// public static string NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 55095208a6..b4418b67ce 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10092,6 +10092,9 @@ When you configure an NFS storage repository, you simply provide the host name o Now + + NRPE + Changing NRPE configuration... @@ -10099,13 +10102,13 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE service is active - Allow hosts should not be empty. + Monitoring servers should not be empty. - Allow hosts format is not correct + Monitoring servers format is not correct - Allow hosts should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com + Monitoring servers should be comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com Comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com @@ -10156,16 +10159,16 @@ When you configure an NFS storage repository, you simply provide the host name o Threshold value should range from {0} to {1}. - Threshold value should be 3 numbers separated with comma. + Threshold value should consist of 3 comma separated numbers. - Threshold value should be number. + Threshold value should be a number. Threshold value should not be empty. - Warning threshold should be bigger than critical threshold. + Warning threshold should be greater than critical threshold. Warning threshold should be less than critical threshold. From a720105fb9a3b8368b6a8a1531dd551bf87afebd Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Sun, 8 Oct 2023 16:03:18 +0800 Subject: [PATCH 06/31] Rename private instance class fields name, add parameters changing check, etc. --- XenAdmin/Dialogs/PropertiesDialog.cs | 3 +- .../SettingsPanels/NRPEEditPage.CheckGroup.cs | 273 ----------- .../SettingsPanels/NRPEEditPage.Designer.cs | 65 ++- XenAdmin/SettingsPanels/NRPEEditPage.cs | 443 +++++++++++------- XenAdmin/SettingsPanels/NRPEEditPage.resx | 285 +++++++---- XenAdmin/XenAdmin.csproj | 3 - XenModel/Actions/NRPE/CheckGroup.cs | 267 +++++++++++ .../Actions/NRPE/NRPEHostConfiguration.cs | 27 +- XenModel/Actions/NRPE/NRPERetrieveAction.cs | 163 +++++++ XenModel/Actions/NRPE/NRPEUpdateAction.cs | 56 +-- XenModel/Messages.Designer.cs | 47 +- XenModel/Messages.resx | 19 +- XenModel/XenModel.csproj | 3 + 13 files changed, 1069 insertions(+), 585 deletions(-) delete mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs create mode 100644 XenModel/Actions/NRPE/CheckGroup.cs create mode 100644 XenModel/Actions/NRPE/NRPERetrieveAction.cs diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index b35caaf895..8c6f9de77d 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -318,7 +318,8 @@ private void Build() dialog.ShowDialog(Program.MainWindow); } } - if (isHost || isPool) + if ((isHost || isPool) && + (connection.Session.IsLocalSuperuser || connection.Session.Roles.Any(r => r.name_label == Role.MR_ROLE_POOL_ADMIN))) { NRPEEditPage = new NRPEEditPage(); ShowTab(NRPEEditPage); diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs deleted file mode 100644 index 3a779a3bdb..0000000000 --- a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs +++ /dev/null @@ -1,273 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System.Drawing; -using System.Windows.Forms; - -namespace XenAdmin.SettingsPanels -{ - public partial class NRPEEditPage - { - - public class CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "80"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "90"; - - private readonly decimal THRESHOLD_MINIMUM = 0.1M; - private readonly decimal THRESHOLD_MAXIMUM = 100M; - - private string name; - private string warningThresholdDefault; - private string criticalThresholdDefault; - - protected DataGridViewRow checkThresholdRow; - protected DataGridViewTextBoxCell nameCell; - protected DataGridViewTextBoxCell warningThresholdCell; - protected DataGridViewTextBoxCell criticalThresholdCell; - - public string Name { get => name; set => name = value; } - public string WarningThresholdDefault { get => warningThresholdDefault; set => warningThresholdDefault = value; } - public string CriticalThresholdDefault { get => criticalThresholdDefault; set => criticalThresholdDefault = value; } - public DataGridViewRow CheckThresholdRow { get => checkThresholdRow; set => checkThresholdRow = value; } - public DataGridViewTextBoxCell NameCell { get => nameCell; set => nameCell = value; } - public DataGridViewTextBoxCell WarningThresholdCell { get => warningThresholdCell; set => warningThresholdCell = value; } - public DataGridViewTextBoxCell CriticalThresholdCell { get => criticalThresholdCell; set => criticalThresholdCell = value; } - - public CheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) - { - InitCheckGroup(name, labelName, warningThresholdDefaultValue, criticalThresholdDefaultValue); - } - - public CheckGroup(string name, string labelName) - { - InitCheckGroup(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD); - } - - private void InitCheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) - { - Name = name; - nameCell = new DataGridViewTextBoxCell { Value = labelName }; - warningThresholdDefault = warningThresholdDefaultValue; - criticalThresholdDefault = criticalThresholdDefaultValue; - warningThresholdCell = new DataGridViewTextBoxCell { Value = warningThresholdDefaultValue }; - criticalThresholdCell = new DataGridViewTextBoxCell { Value = criticalThresholdDefaultValue }; - checkThresholdRow = new DataGridViewRow(); - checkThresholdRow.Cells.AddRange(nameCell, warningThresholdCell, criticalThresholdCell); - checkThresholdRow.DefaultCellStyle.Format = "N2"; - checkThresholdRow.DefaultCellStyle.NullValue = 0; - warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - } - - public void UpdateThreshold(string warningThreshold, string criticalThreshold) - { - warningThresholdCell.Value = warningThreshold; - criticalThresholdCell.Value = criticalThreshold; - warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - } - - public virtual bool CheckValue() - { - warningThresholdCell.ErrorText = ""; - criticalThresholdCell.ErrorText = ""; - checkThresholdRow.DataGridView.ShowCellToolTips = false; - - if (IsEmptyForPool()) - { - return true; - } - - if (CheckEachValue(warningThresholdCell) && - CheckEachValue(criticalThresholdCell) && - CompareWarningAndCritical() && - CheckModifyAllForPool()) - { - return true; - } - - checkThresholdRow.DataGridView.ShowCellToolTips = true; - return false; - } - - private bool IsEmptyForPool() - { - return warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)); - } - - protected virtual bool CheckEachValue(DataGridViewTextBoxCell cell) - { - string thresholdStr = cell.Value.ToString().Trim(); - if (thresholdStr.Equals("")) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - if (!decimal.TryParse(thresholdStr, out decimal threshold)) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_NUMBER); - return false; - } - if (threshold < THRESHOLD_MINIMUM || threshold > THRESHOLD_MAXIMUM) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_RANGE_ERROR, THRESHOLD_MINIMUM, THRESHOLD_MAXIMUM); - return false; - } - cell.ErrorText = ""; - return true; - } - - protected virtual bool CompareWarningAndCritical() - { - decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); - decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); - if (warningDecimal < criticalDecimal) - { - warningThresholdCell.ErrorText = ""; - return true; - } - else - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); - return false; - } - } - - private bool CheckModifyAllForPool() - { - if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) - { - criticalThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - else if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - return true; - } - } - - public class FreeCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "20"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "10"; - - public FreeCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - - protected override bool CompareWarningAndCritical() - { - decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); - decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); - if (warningDecimal > criticalDecimal) - { - warningThresholdCell.ErrorText = ""; - return true; - } - else - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL); - return false; - } - } - - } - - public class HostLoadCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "3"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "4"; - - public HostLoadCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - } - - public class Dom0LoadCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "2.7,2.6,2.5"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "3.2,3.1,3"; - - public Dom0LoadCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - - protected override bool CompareWarningAndCritical() - { - string[] warningArray = warningThresholdCell.Value.ToString().Split(','); - string[] criticalArray = criticalThresholdCell.Value.ToString().Split(','); - for (int i = 0; i < 3; i++) - { - decimal.TryParse(warningArray[i].Trim(), out decimal warningDecimal); - decimal.TryParse(criticalArray[i].Trim(), out decimal criticalDecimal); - if (warningDecimal > criticalDecimal) - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); - return false; - } - } - warningThresholdCell.ErrorText = ""; - return true; - } - - protected override bool CheckEachValue(DataGridViewTextBoxCell cell) - { - checkThresholdRow.DataGridView.ShowCellToolTips = true; - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS); - string[] loadArray = cell.Value.ToString().Split(','); - if (loadArray.Length != 3) - { - return false; - } - foreach (string load in loadArray) - { - bool isDecimal = decimal.TryParse(load, out _); - if (!isDecimal) - { - return false; - } - } - cell.ErrorText = ""; - checkThresholdRow.DataGridView.ShowCellToolTips = false; - return true; - } - } - } -} diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index 5a157e6e75..a3fcc3103b 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -30,9 +30,9 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NRPEEditPage)); this.NRPETableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); - this.descLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.DescLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); this.GeneralConfigureGroupBox = new System.Windows.Forms.GroupBox(); this.GeneralConfigTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.AllowHostsLabel = new System.Windows.Forms.Label(); @@ -43,38 +43,44 @@ private void InitializeComponent() this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); + this.RetrieveNRPELabel = new System.Windows.Forms.Label(); + this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); this.NRPETableLayoutPanel.SuspendLayout(); this.GeneralConfigureGroupBox.SuspendLayout(); this.GeneralConfigTableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); + this.RetrieveNRPEPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).BeginInit(); this.SuspendLayout(); // // NRPETableLayoutPanel // resources.ApplyResources(this.NRPETableLayoutPanel, "NRPETableLayoutPanel"); - this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 2); this.NRPETableLayoutPanel.Controls.Add(this.DescLabelPool, 0, 0); - this.NRPETableLayoutPanel.Controls.Add(this.descLabelHost, 0, 1); + this.NRPETableLayoutPanel.Controls.Add(this.DescLabelHost, 0, 1); + this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 2); this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 3); this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 4); + this.NRPETableLayoutPanel.Controls.Add(this.RetrieveNRPEPanel, 0, 5); this.NRPETableLayoutPanel.Name = "NRPETableLayoutPanel"; // - // EnableNRPECheckBox - // - resources.ApplyResources(this.EnableNRPECheckBox, "EnableNRPECheckBox"); - this.EnableNRPECheckBox.Name = "EnableNRPECheckBox"; - this.EnableNRPECheckBox.UseVisualStyleBackColor = true; - this.EnableNRPECheckBox.CheckedChanged += new System.EventHandler(this.EnableNRPECheckBox_CheckedChanged); - // // DescLabelPool // resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); this.DescLabelPool.Name = "DescLabelPool"; // - // descLabelHost + // DescLabelHost + // + resources.ApplyResources(this.DescLabelHost, "DescLabelHost"); + this.DescLabelHost.Name = "DescLabelHost"; + // + // EnableNRPECheckBox // - resources.ApplyResources(this.descLabelHost, "descLabelHost"); - this.descLabelHost.Name = "descLabelHost"; + resources.ApplyResources(this.EnableNRPECheckBox, "EnableNRPECheckBox"); + this.EnableNRPECheckBox.Name = "EnableNRPECheckBox"; + this.EnableNRPECheckBox.UseVisualStyleBackColor = true; + this.EnableNRPECheckBox.CheckedChanged += new System.EventHandler(this.EnableNRPECheckBox_CheckedChanged); // // GeneralConfigureGroupBox // @@ -120,12 +126,12 @@ private void InitializeComponent() // this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.CheckDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); this.CheckDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.CheckColumn, this.WarningThresholdColumn, this.CriticalThresholdColumn}); - resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; this.CheckDataGridView.Name = "CheckDataGridView"; this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; @@ -152,6 +158,24 @@ private void InitializeComponent() resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; // + // RetrieveNRPEPanel + // + resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPELabel, 1, 0); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPEPicture, 0, 0); + this.RetrieveNRPEPanel.Name = "RetrieveNRPEPanel"; + // + // RetrieveNRPELabel + // + resources.ApplyResources(this.RetrieveNRPELabel, "RetrieveNRPELabel"); + this.RetrieveNRPELabel.Name = "RetrieveNRPELabel"; + // + // RetrieveNRPEPicture + // + resources.ApplyResources(this.RetrieveNRPEPicture, "RetrieveNRPEPicture"); + this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; + this.RetrieveNRPEPicture.TabStop = false; + // // NRPEEditPage // resources.ApplyResources(this, "$this"); @@ -165,8 +189,9 @@ private void InitializeComponent() this.GeneralConfigTableLayoutPanel.ResumeLayout(false); this.GeneralConfigTableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); + this.RetrieveNRPEPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).EndInit(); this.ResumeLayout(false); - this.PerformLayout(); } @@ -181,9 +206,13 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox DebugLogCheckBox; private System.Windows.Forms.CheckBox SslDebugLogCheckBox; private Controls.DataGridViewEx.DataGridViewEx CheckDataGridView; - private Controls.Common.AutoHeightLabel descLabelHost; + private Controls.Common.AutoHeightLabel DescLabelHost; private System.Windows.Forms.DataGridViewTextBoxColumn CheckColumn; private System.Windows.Forms.DataGridViewTextBoxColumn WarningThresholdColumn; private System.Windows.Forms.DataGridViewTextBoxColumn CriticalThresholdColumn; + private System.Windows.Forms.Label RetrieveNRPELabel; + private System.Windows.Forms.TableLayoutPanel RetrieveNRPEPanel; + private System.Windows.Forms.PictureBox RetrieveNRPEPicture; } -} \ No newline at end of file +} + \ No newline at end of file diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index ccf22e2e3a..8193664289 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -37,7 +37,7 @@ using XenAdmin.Core; using XenAdmin.Actions.NRPE; using XenAPI; - +using System.Linq; namespace XenAdmin.SettingsPanels { @@ -51,31 +51,16 @@ public partial class NRPEEditPage : UserControl, IEditPage private bool _isHost; - private IXenObject Clone; - private readonly ToolTip InvalidParamToolTip; - private string InvalidParamToolTipText = ""; - - private readonly List CheckGroupList = new List(); - private readonly Dictionary CheckGroupDictByName = new Dictionary(); - private readonly Dictionary CheckGroupDictByLabel = new Dictionary(); + private IXenObject _clone; + private readonly ToolTip _invalidParamToolTip; + private string _invalidParamToolTipText = ""; - private NRPEHostConfiguration NRPEOriginalConfig; - private NRPEHostConfiguration NRPECurrentConfig; + private readonly List _checkGroupList = new List(); + private readonly Dictionary _checkGroupDictByName = new Dictionary(); + private readonly Dictionary _checkGroupDictByLabel = new Dictionary(); - public string SubText - { - get - { - if (_isHost) - { - return EnableNRPECheckBox.Checked ? Messages.NRPE_ACTIVE : Messages.NRPE_INACTIVE; - } - else - { - return Messages.NRPE_BATCH_CONFIGURATION; - } - } - } + private NRPEHostConfiguration _nrpeOriginalConfig; + private NRPEHostConfiguration _nrpeCurrentConfig; public Image Image => Images.StaticImages._000_Module_h32bit_16; @@ -84,61 +69,70 @@ public NRPEEditPage() InitializeComponent(); Text = Messages.NRPE; - NRPECurrentConfig = new NRPEHostConfiguration + _nrpeOriginalConfig = new NRPEHostConfiguration { EnableNRPE = false, AllowHosts = NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER, Debug = false, SslLogging = false }; - NRPEOriginalConfig = (NRPEHostConfiguration) NRPECurrentConfig.Clone(); - - EnableNRPECheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "enableNRPE"); - AllowHostsTextBox.DataBindings.Add("Text", NRPECurrentConfig, "allowHosts"); - DebugLogCheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "debug"); - SslDebugLogCheckBox.DataBindings.Add("Checked", NRPECurrentConfig, "sslLogging"); - - CheckGroupList.Add(new HostLoadCheckGroup("check_host_load", Messages.NRPE_CHECK_HOST_LOAD)); - CheckGroupList.Add(new CheckGroup("check_host_cpu", Messages.NRPE_CHECK_HOST_CPU)); - CheckGroupList.Add(new CheckGroup("check_host_memory", Messages.NRPE_CHECK_HOST_MEMORY)); - CheckGroupList.Add(new CheckGroup("check_vgpu", Messages.NRPE_CHECK_VGPU)); - CheckGroupList.Add(new CheckGroup("check_vgpu_memory", Messages.NRPE_CHECK_VGPU_MEMORY)); - CheckGroupList.Add(new Dom0LoadCheckGroup("check_load", Messages.NRPE_CHECK_LOAD)); - CheckGroupList.Add(new CheckGroup("check_cpu", Messages.NRPE_CHECK_CPU)); - CheckGroupList.Add(new CheckGroup("check_memory", Messages.NRPE_CHECK_MEMORY)); - CheckGroupList.Add(new FreeCheckGroup("check_swap", Messages.NRPE_CHECK_SWAP)); - CheckGroupList.Add(new FreeCheckGroup("check_disk_root", Messages.NRPE_CHECK_DISK_ROOT)); - CheckGroupList.Add(new FreeCheckGroup("check_disk_log", Messages.NRPE_CHECK_DISK_LOG)); - - foreach (CheckGroup checkGroup in CheckGroupList) + + _checkGroupList.Add(new HostLoadCheckGroup("check_host_load", Messages.NRPE_CHECK_HOST_LOAD)); + _checkGroupList.Add(new CheckGroup("check_host_cpu", Messages.NRPE_CHECK_HOST_CPU)); + _checkGroupList.Add(new CheckGroup("check_host_memory", Messages.NRPE_CHECK_HOST_MEMORY)); + _checkGroupList.Add(new CheckGroup("check_vgpu", Messages.NRPE_CHECK_VGPU)); + _checkGroupList.Add(new CheckGroup("check_vgpu_memory", Messages.NRPE_CHECK_VGPU_MEMORY)); + _checkGroupList.Add(new Dom0LoadCheckGroup("check_load", Messages.NRPE_CHECK_LOAD)); + _checkGroupList.Add(new CheckGroup("check_cpu", Messages.NRPE_CHECK_CPU)); + _checkGroupList.Add(new CheckGroup("check_memory", Messages.NRPE_CHECK_MEMORY)); + _checkGroupList.Add(new FreeCheckGroup("check_swap", Messages.NRPE_CHECK_SWAP)); + _checkGroupList.Add(new FreeCheckGroup("check_disk_root", Messages.NRPE_CHECK_DISK_ROOT)); + _checkGroupList.Add(new FreeCheckGroup("check_disk_log", Messages.NRPE_CHECK_DISK_LOG)); + + foreach (CheckGroup checkGroup in _checkGroupList) { CheckDataGridView.Rows.Add(checkGroup.CheckThresholdRow); - CheckGroupDictByName.Add(checkGroup.Name, checkGroup); - CheckGroupDictByLabel.Add(checkGroup.NameCell.Value.ToString(), checkGroup); + _checkGroupDictByName.Add(checkGroup.Name, checkGroup); + _checkGroupDictByLabel.Add(checkGroup.NameCell.Value.ToString(), checkGroup); } - UpdateOtherComponentBasedEnableNRPECheckBox(); - AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); AllowHostsTextBox.GotFocus += AllowHostsTextBox_GotFocus; AllowHostsTextBox.LostFocus += AllowHostsTextBox_LostFocus; - InvalidParamToolTip = new ToolTip + _invalidParamToolTip = new ToolTip { IsBalloon = true, ToolTipIcon = ToolTipIcon.Warning, ToolTipTitle = Messages.INVALID_PARAMETER, Tag = AllowHostsTextBox }; + DisableAllComponent(); + } + + public string SubText + { + get + { + if (_isHost) + { + return Messages.NRPE_EDIT_PAGE_TEXT; + } + else + { + return Messages.NRPE_BATCH_CONFIGURATION; + } + } } public bool ValidToSave { get { - InvalidParamToolTipText = ""; - InvalidParamToolTip.ToolTipTitle = ""; + _invalidParamToolTipText = ""; + _invalidParamToolTip.ToolTipTitle = ""; CheckDataGridView.ShowCellToolTips = false; + CheckDataGridView.ShowCellErrors = false; if (!EnableNRPECheckBox.Checked) { @@ -147,10 +141,12 @@ public bool ValidToSave bool valid = IsAllowHostsValid(); - foreach (CheckGroup checkGroup in CheckGroupList) + foreach (CheckGroup checkGroup in _checkGroupList) { if (!checkGroup.CheckValue()) { + CheckDataGridView.ShowCellToolTips = true; + CheckDataGridView.ShowCellErrors = true; valid = false; } } @@ -162,7 +158,15 @@ public bool HasChanged { get { - return true; + UpdateCurrentNRPEConfiguration(); + if (_isHost) + { + return IsNRPEConfigurationChanged(); + } + else + { + return true; + } } } @@ -172,171 +176,269 @@ public void Cleanup() public void ShowLocalValidationMessages() { - if (InvalidParamToolTip.Tag is Control ctrl) + if (_invalidParamToolTip.Tag is Control ctrl) { - InvalidParamToolTip.Hide(ctrl); - if (!InvalidParamToolTipText.Equals("")) + _invalidParamToolTip.Hide(ctrl); + if (!_invalidParamToolTipText.Equals("")) { - HelpersGUI.ShowBalloonMessage(ctrl, InvalidParamToolTip, InvalidParamToolTipText); + HelpersGUI.ShowBalloonMessage(ctrl, _invalidParamToolTip, _invalidParamToolTipText); } } } public void HideLocalValidationMessages() { - if (InvalidParamToolTip.Tag is Control ctrl) + if (_invalidParamToolTip.Tag is Control ctrl) { - InvalidParamToolTip.Hide(ctrl); + _invalidParamToolTip.Hide(ctrl); } } - public void SetXenObjects(IXenObject orig, IXenObject clone) + public AsyncAction SaveSettings() { - Clone = clone; - _isHost = Clone is Host; - - descLabelHost.Visible = _isHost; - DescLabelPool.Visible = !_isHost; - - if (_isHost) - { - InitNRPEGeneralConfiguration(); - InitNRPEThreshold(); - } + return new NRPEUpdateAction(_clone, _nrpeCurrentConfig, _nrpeOriginalConfig, true); } - public AsyncAction SaveSettings() + public bool IsNRPEAvailable(IXenObject clone) { - foreach (KeyValuePair item in CheckGroupDictByName) + IXenObject checkHost; + if (clone is Host h) { - if (item.Value.WarningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) - && item.Value.CriticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) - { - NRPECurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, - item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); - } + checkHost = h; } - return new NRPEUpdateAction(Clone, NRPECurrentConfig, NRPEOriginalConfig, false); + else if (clone is Pool p) + { + List hostList = p.Connection.Cache.Hosts.ToList(); + checkHost = hostList[0]; + } + else + { + return false; + } + try + { + Host.call_plugin(checkHost.Connection.Session, checkHost.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); + } + catch (Exception e) + { + log.InfoFormat("Execute NRPE plugin failed, failed reason: {0}. It may not support NRPE.", e.Message); + return false; + } + return true; } - private void InitNRPEGeneralConfiguration() + public void SetXenObjects(IXenObject orig, IXenObject clone) { - string status = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_STATUS, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); - NRPECurrentConfig.EnableNRPE = status.Trim().Equals("active enabled"); - - string nrpeConfig = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); + _clone = clone; + _isHost = _clone is Host; - string[] nrpeConfigArray = nrpeConfig.Split('\n'); - foreach (string nrpeConfigItem in nrpeConfigArray) - { - if (nrpeConfigItem.Trim().StartsWith("allowed_hosts:")) - { - string allowHosts = nrpeConfigItem.Replace("allowed_hosts:", "").Trim(); - NRPECurrentConfig.AllowHosts = AllowHostsWithoutLocalAddress(allowHosts); - AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? - Color.FromKnownColor(KnownColor.ControlDark) : Color.FromKnownColor(KnownColor.ControlText); - } - else if (nrpeConfigItem.Trim().StartsWith("debug:")) - { - string enableDebug = nrpeConfigItem.Replace("debug:", "").Trim(); - NRPECurrentConfig.Debug = enableDebug.Equals(NRPEHostConfiguration.DEBUG_ENABLE); - } - else if (nrpeConfigItem.Trim().StartsWith("ssl_logging:")) - { - string enableSslLogging = nrpeConfigItem.Replace("ssl_logging:", "").Trim(); - NRPECurrentConfig.SslLogging = enableSslLogging.Equals(NRPEHostConfiguration.SSL_LOGGING_ENABLE); - } - } - NRPEOriginalConfig = (NRPEHostConfiguration) NRPECurrentConfig.Clone(); + DescLabelHost.Visible = _isHost; + DescLabelPool.Visible = !_isHost; + UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus.Retrieving); + DisableAllComponent(); - UpdateOtherComponentBasedEnableNRPECheckBox(); + NRPERetrieveAction action = new NRPERetrieveAction(_clone, _nrpeOriginalConfig, _checkGroupDictByName, true); + action.Completed += ActionCompleted; + action.RunAsync(); } - private void InitNRPEThreshold() + private void ActionCompleted(ActionBase sender) { - string nrpeThreshold = Host.call_plugin(Clone.Connection.Session, Clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); + Program.Invoke(this.Parent, UpdateRetrieveStatus); + } - string[] nrpeThresholdArray = nrpeThreshold.Split('\n'); - foreach (string nrpeThresholdItem in nrpeThresholdArray) + private void UpdateRetrieveStatus() + { + if (_nrpeOriginalConfig.Status == NRPEHostConfiguration.RetrieveNRPEStatus.Successful) { - // Return string format for each line: check_cpu warning threshold - 50 critical threshold - 80 - string[] thresholdRtnArray = nrpeThresholdItem.Split(' '); - string checkName = thresholdRtnArray[0]; - if (CheckGroupDictByName.TryGetValue(thresholdRtnArray[0], out CheckGroup thresholdCheck)) - { - string warningThreshold = thresholdRtnArray[4]; - string criticalThreshold = thresholdRtnArray[8]; - thresholdCheck.UpdateThreshold(warningThreshold, criticalThreshold); - NRPEOriginalConfig.AddNRPECheck(new NRPEHostConfiguration.Check(checkName, warningThreshold, criticalThreshold)); - } + AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? + Color.FromKnownColor(KnownColor.ControlDark) : Color.FromKnownColor(KnownColor.ControlText); + UpdateOtherComponentBasedEnableNRPECheckBox(); + UpdateComponentBasedConfiguration(); } + UpdateRetrievingNRPETip(_nrpeOriginalConfig.Status); } - private bool IsAllowHostsValid() + private void UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus status) { - InvalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; - InvalidParamToolTip.Tag = AllowHostsTextBox; - CheckDataGridView.ShowCellToolTips = true; - - string str = AllowHostsTextBox.Text; - if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) + switch (status) { - InvalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_EMPTY_ERROR; - return false; + case NRPEHostConfiguration.RetrieveNRPEStatus.Retrieving: + RetrieveNRPELabel.Text = Messages.NRPE_RETRIEVING_CONFIGURATION; + RetrieveNRPEPicture.Image = Images.StaticImages.ajax_loader; + RetrieveNRPEPicture.Visible = true; + break; + case NRPEHostConfiguration.RetrieveNRPEStatus.Successful: + RetrieveNRPELabel.Text = ""; + RetrieveNRPEPicture.Image = Images.StaticImages._000_Tick_h32bit_16; + RetrieveNRPEPicture.Visible = false; + break; + case NRPEHostConfiguration.RetrieveNRPEStatus.Failed: + RetrieveNRPELabel.Text = Messages.NRPE_RETRIEVE_FAILED; + RetrieveNRPEPicture.Image = Images.StaticImages._000_error_h32bit_16; + RetrieveNRPEPicture.Visible = true; + break; + case NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport: + RetrieveNRPELabel.Text = Messages.NRPE_UNSUPPORT; + RetrieveNRPEPicture.Image = Images.StaticImages._000_error_h32bit_16; + RetrieveNRPEPicture.Visible = true; + break; + default: + break; } + } - string[] hostArray = str.Split(','); - foreach (string host in hostArray) + private void DisableAllComponent() + { + EnableNRPECheckBox.Enabled = false; + GeneralConfigureGroupBox.Enabled = false; + CheckDataGridView.Enabled = false; + } + + private bool IsAllowHostsValid() + { + _invalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; + _invalidParamToolTip.Tag = AllowHostsTextBox; + CheckDataGridView.ShowCellToolTips = true; + + string str = AllowHostsTextBox.Text; + if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_EMPTY_ERROR; + return false; + } + + string[] hostArray = str.Split(','); + for ( int i = 0; i < hostArray.Length; i++ ) + { + if (!REGEX_IPV4.Match(hostArray[i].Trim()).Success && + !REGEX_IPV4_CIDR.Match(hostArray[i].Trim()).Success && + !REGEX_DOMAIN.Match(hostArray[i].Trim()).Success) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; + return false; + } + for ( int j = 0; j < i; j++ ) + { + if (hostArray[i].Trim().Equals(hostArray[j].Trim())) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_SAME_ADDRESS; + return false; + } + } + } + foreach (string host in hostArray) + { + if (!REGEX_IPV4.Match(host.Trim()).Success && + !REGEX_IPV4_CIDR.Match(host.Trim()).Success && + !REGEX_DOMAIN.Match(host.Trim()).Success) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; + return false; + } + } + CheckDataGridView.ShowCellToolTips = false; + return true; + } + + private string AllowHostsWithoutLocalAddress(string allowHosts) + { + string UpdatedAllowHosts = ""; + string[] AllowHostArray = allowHosts.Split(','); + foreach (string allowHost in AllowHostArray) + { + if (!allowHost.Trim().Equals("127.0.0.1") && + !allowHost.Trim().Equals("::1")) + { + UpdatedAllowHosts += allowHost + ","; + } + } + return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : + UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + } + + private void UpdateOtherComponentBasedEnableNRPECheckBox() + { + GeneralConfigureGroupBox.Enabled = EnableNRPECheckBox.Checked; + UpdateCheckDataGridViewAvailableStatus(); + } + + private void UpdateComponentBasedConfiguration() + { + EnableNRPECheckBox.Enabled = true; + EnableNRPECheckBox.Checked = _nrpeOriginalConfig.EnableNRPE; + AllowHostsTextBox.Text = AllowHostsWithoutLocalAddress(_nrpeOriginalConfig.AllowHosts); + AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? + Color.FromKnownColor(KnownColor.ControlDark) : AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + DebugLogCheckBox.Checked = _nrpeOriginalConfig.Debug; + SslDebugLogCheckBox.Checked = _nrpeOriginalConfig.SslLogging; + UpdateCheckDataGridViewAvailableStatus(); + } + + private void UpdateCheckDataGridViewAvailableStatus() + { + CheckDataGridView.Enabled = EnableNRPECheckBox.Checked; + CheckDataGridView.DefaultCellStyle.BackColor = EnableNRPECheckBox.Checked ? + Color.FromKnownColor(KnownColor.Window) : Color.FromKnownColor(KnownColor.Control); + if (_isHost) { - if (!REGEX_IPV4.Match(host.Trim()).Success && - !REGEX_IPV4_CIDR.Match(host.Trim()).Success && - !REGEX_DOMAIN.Match(host.Trim()).Success) + foreach (var checkGroup in _checkGroupList) { - InvalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; - return false; + if (EnableNRPECheckBox.Checked) + { + checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + else + { + checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + } } } - CheckDataGridView.ShowCellToolTips = false; - return true; } - private string AllowHostsWithoutLocalAddress(string allowHosts) + private bool IsNRPEConfigurationChanged() { - string UpdatedAllowHosts = ""; - string[] AllowHostArray = allowHosts.Split(','); - foreach (string allowHost in AllowHostArray) + if (_nrpeCurrentConfig.EnableNRPE != _nrpeOriginalConfig.EnableNRPE || + !_nrpeCurrentConfig.AllowHosts.Equals(_nrpeOriginalConfig.AllowHosts) || + _nrpeCurrentConfig.Debug != _nrpeOriginalConfig.Debug || + _nrpeCurrentConfig.SslLogging != _nrpeOriginalConfig.SslLogging) + { + return true; + } + foreach (KeyValuePair kvp in _nrpeCurrentConfig.CheckDict) { - if (!allowHost.Trim().Equals("127.0.0.1") && - !allowHost.Trim().Equals("::1")) + NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); + if (CurrentCheck != null && OriginalCheck != null + && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) + || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) { - UpdatedAllowHosts += allowHost + ","; + return true; } } - return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : - UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + return false; } - private void UpdateOtherComponentBasedEnableNRPECheckBox() + private void UpdateCurrentNRPEConfiguration() { - if (EnableNRPECheckBox.Checked) + _nrpeCurrentConfig = new NRPEHostConfiguration { - GeneralConfigureGroupBox.Enabled = true; - CheckDataGridView.Enabled = true; - CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Window); - CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Window); - } - else + EnableNRPE = EnableNRPECheckBox.Checked, + AllowHosts = AllowHostsTextBox.Text, + Debug = DebugLogCheckBox.Checked, + SslLogging = SslDebugLogCheckBox.Checked + }; + foreach (KeyValuePair item in _checkGroupDictByName) { - GeneralConfigureGroupBox.Enabled = false; - CheckDataGridView.Enabled = false; - CheckDataGridView.BackgroundColor = Color.FromKnownColor(KnownColor.Control); - CheckDataGridView.DefaultCellStyle.BackColor = Color.FromKnownColor(KnownColor.Control); + if (item.Value.WarningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) + && item.Value.CriticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) + { + _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, + item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); + } } } @@ -350,8 +452,8 @@ private void AllowHostsTextBox_GotFocus(object sender, EventArgs e) if (AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) { AllowHostsTextBox.Text = ""; - AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); } + AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); } private void AllowHostsTextBox_LostFocus(object sender, EventArgs e) @@ -381,7 +483,7 @@ private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs if (currentCell != null &&!_isHost && currentCell.Value.ToString().Trim().Equals("")) { currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - CheckGroupDictByLabel.TryGetValue(CheckDataGridView.CurrentRow.Cells[0].Value.ToString(), out CheckGroup checkGroup); + _checkGroupDictByLabel.TryGetValue(CheckDataGridView.CurrentRow.Cells[0].Value.ToString(), out CheckGroup checkGroup); if (checkGroup != null) { @@ -390,6 +492,7 @@ private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs else if (currentCell.ColumnIndex == CriticalThresholdColumn.Index) currentCell.Value = checkGroup.CriticalThresholdDefault; } + _nrpeOriginalConfig.CheckDict.TryGetValue(checkGroup.Name, out NRPEHostConfiguration.Check check); } } } diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx index 434ae82164..b8734a0554 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.resx +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -118,67 +118,28 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True - 1 - - True - - - - NoControl - - - - 3, 88 - - - 3, 3, 3, 8 - - - 3, 0, 0, 0 - - - 95, 17 - - - 2 - - - &Enable NRPE - - - EnableNRPECheckBox - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - NRPETableLayoutPanel - - - 0 - True + Fill NoControl + - 3, 0 + 4, 0 - 3, 0, 3, 10 + 4, 0, 4, 15 - 644, 39 + 967, 39 0 @@ -197,40 +158,79 @@ This page does not offer an overview of the NRPE configuration and metric thresh NRPETableLayoutPanel - 1 + 0 - + True - + Fill - - 3, 49 + + NoControl + + + 4, 54 - - 3, 0, 3, 10 + + 4, 0, 4, 15 - - 644, 26 + + 967, 26 - + 1 - + Nagios Remote Plugin Executor (NRPE) allows you to monitor remotely resource metrics on the servers of your pool. Use this page to review and modify the NRPE configuration and metric threshold settings used for this server. - - descLabelHost + + DescLabelHost - + XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - + NRPETableLayoutPanel - + + 1 + + + True + + + NoControl + + + 4, 99 + + + 4, 4, 4, 12 + + + 4, 0, 0, 0 + + + 103, 21 + + + 2 + + + &Enable NRPE + + + EnableNRPECheckBox + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + 2 @@ -252,7 +252,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 6 + 4, 7 + + + 4, 0, 4, 0 96, 13 @@ -279,10 +282,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s Left, Right - 105, 3 + 108, 4 + + + 4, 4, 4, 4 - 530, 20 + 847, 20 1 @@ -306,13 +312,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 29 + 4, 32 + + + 4, 4, 4, 4 - 3, 0, 0, 0 + 4, 0, 0, 0 - 211, 17 + 219, 21 2 @@ -339,13 +348,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 52 + 4, 61 + + + 4, 4, 4, 4 - 3, 0, 0, 0 + 4, 0, 0, 0 - 181, 17 + 189, 21 3 @@ -369,13 +381,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s Top - 3, 16 + 4, 17 + + + 4, 4, 4, 4 3 - 638, 72 + 959, 86 0 @@ -393,22 +408,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,20" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,30" /></TableLayoutSettings> Fill - 3, 116 + 4, 136 - 3, 3, 3, 10 + 4, 4, 4, 15 - 3, 3, 3, 0 + 4, 4, 4, 0 - 644, 100 + 967, 150 3 @@ -428,6 +443,9 @@ Use this page to review and modify the NRPE configuration and metric threshold s 3 + + 34 + Metric @@ -456,10 +474,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s Fill - 3, 229 + 4, 305 + + + 4, 4, 4, 4 + + + 62 - 644, 305 + 967, 450 4 @@ -476,6 +500,96 @@ Use this page to review and modify the NRPE configuration and metric threshold s 4 + + True + + + 2 + + + Top, Bottom, Left, Right + + + NoControl + + + 35, 0 + + + 4, 0, 4, 0 + + + 930, 31 + + + 5 + + + Retrieving NRPE configuration... + + + MiddleLeft + + + RetrieveNRPELabel + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + RetrieveNRPEPanel + + + 0 + + + 3, 3 + + + 25, 25 + + + 6 + + + RetrieveNRPEPicture + + + System.Windows.Forms.PictureBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + RetrieveNRPEPanel + + + 1 + + + 3, 762 + + + 1 + + + 969, 31 + + + 6 + + + RetrieveNRPEPanel + + + System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 5 + + + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="RetrieveNRPELabel" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="RetrieveNRPEPicture" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="Percent,100" /></TableLayoutSettings> + Fill @@ -483,13 +597,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0, 0 - 3, 10, 3, 3 + 4, 15, 4, 0 - 5 + 7 - 650, 537 + 975, 806 0 @@ -507,19 +621,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="EnableNRPECheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="descLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,10" /></TableLayoutSettings> True - 96, 96 + 144, 144 True + + 4, 4, 4, 4 + - 650, 537 + 975, 806 CheckColumn diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index 11b51bdb1f..26125ed37f 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -483,9 +483,6 @@ NRPEEditPage.cs - - UserControl - UserControl diff --git a/XenModel/Actions/NRPE/CheckGroup.cs b/XenModel/Actions/NRPE/CheckGroup.cs new file mode 100644 index 0000000000..3b23469d90 --- /dev/null +++ b/XenModel/Actions/NRPE/CheckGroup.cs @@ -0,0 +1,267 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System.Drawing; +using System.Windows.Forms; + +namespace XenAdmin.Actions.NRPE +{ + public class CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "80"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "90"; + + private readonly decimal THRESHOLD_MINIMUM = 0.01M; + private readonly decimal THRESHOLD_MAXIMUM = 100M; + + private string name; + private string warningThresholdDefault; + private string criticalThresholdDefault; + private bool changed; + + protected DataGridViewRow checkThresholdRow; + protected DataGridViewTextBoxCell nameCell; + protected DataGridViewTextBoxCell warningThresholdCell; + protected DataGridViewTextBoxCell criticalThresholdCell; + + public string Name { get => name; set => name = value; } + public string WarningThresholdDefault { get => warningThresholdDefault; set => warningThresholdDefault = value; } + public string CriticalThresholdDefault { get => criticalThresholdDefault; set => criticalThresholdDefault = value; } + public bool Changed { get => changed; set => changed = value; } + public DataGridViewRow CheckThresholdRow { get => checkThresholdRow; set => checkThresholdRow = value; } + public DataGridViewTextBoxCell NameCell { get => nameCell; set => nameCell = value; } + public DataGridViewTextBoxCell WarningThresholdCell { get => warningThresholdCell; set => warningThresholdCell = value; } + public DataGridViewTextBoxCell CriticalThresholdCell { get => criticalThresholdCell; set => criticalThresholdCell = value; } + + public CheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) + { + InitCheckGroup(name, labelName, warningThresholdDefaultValue, criticalThresholdDefaultValue); + } + + public CheckGroup(string name, string labelName) + { + InitCheckGroup(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD); + } + + private void InitCheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) + { + Name = name; + nameCell = new DataGridViewTextBoxCell { Value = labelName }; + warningThresholdDefault = warningThresholdDefaultValue; + criticalThresholdDefault = criticalThresholdDefaultValue; + warningThresholdCell = new DataGridViewTextBoxCell { Value = warningThresholdDefaultValue }; + criticalThresholdCell = new DataGridViewTextBoxCell { Value = criticalThresholdDefaultValue }; + checkThresholdRow = new DataGridViewRow(); + checkThresholdRow.Cells.AddRange(nameCell, warningThresholdCell, criticalThresholdCell); + checkThresholdRow.DefaultCellStyle.Format = "N2"; + checkThresholdRow.DefaultCellStyle.NullValue = 0; + warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + } + + public void UpdateThreshold(string warningThreshold, string criticalThreshold) + { + warningThresholdCell.Value = warningThreshold; + criticalThresholdCell.Value = criticalThreshold; + warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + + public virtual bool CheckValue() + { + warningThresholdCell.ErrorText = ""; + criticalThresholdCell.ErrorText = ""; + + if (IsEmptyForPool()) + { + return true; + } + + if (CheckEachValue(warningThresholdCell) && + CheckEachValue(criticalThresholdCell) && + CompareWarningAndCritical() && + CheckModifyAllForPool()) + { + return true; + } + return false; + } + + private bool IsEmptyForPool() + { + return warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)); + } + + protected virtual bool CheckEachValue(DataGridViewTextBoxCell cell) + { + string thresholdStr = cell.Value.ToString().Trim(); + if (thresholdStr.Equals("")) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + if (!decimal.TryParse(thresholdStr, out decimal threshold)) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_NUMBER); + return false; + } + if (threshold < THRESHOLD_MINIMUM || threshold > THRESHOLD_MAXIMUM) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_RANGE_ERROR, THRESHOLD_MINIMUM, THRESHOLD_MAXIMUM); + return false; + } + cell.ErrorText = ""; + return true; + } + + protected virtual bool CompareWarningAndCritical() + { + decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal < criticalDecimal) + { + warningThresholdCell.ErrorText = ""; + return true; + } + else + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + + private bool CheckModifyAllForPool() + { + if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) + { + criticalThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + else if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) + && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + return true; + } + } + + public class FreeCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "20"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "10"; + + public FreeCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + + protected override bool CompareWarningAndCritical() + { + decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + warningThresholdCell.ErrorText = ""; + return true; + } + else + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL); + return false; + } + } + + } + + public class HostLoadCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "3"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "4"; + + public HostLoadCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + } + + public class Dom0LoadCheckGroup : CheckGroup + { + private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "2.7,2.6,2.5"; + private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "3.2,3.1,3"; + + public Dom0LoadCheckGroup(string name, string labelName) + : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) + { + } + + protected override bool CompareWarningAndCritical() + { + string[] warningArray = warningThresholdCell.Value.ToString().Split(','); + string[] criticalArray = criticalThresholdCell.Value.ToString().Split(','); + for (int i = 0; i < 3; i++) + { + decimal.TryParse(warningArray[i].Trim(), out decimal warningDecimal); + decimal.TryParse(criticalArray[i].Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + warningThresholdCell.ErrorText = ""; + return true; + } + + protected override bool CheckEachValue(DataGridViewTextBoxCell cell) + { + checkThresholdRow.DataGridView.ShowCellToolTips = true; + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS); + string[] loadArray = cell.Value.ToString().Split(','); + if (loadArray.Length != 3) + { + return false; + } + foreach (string load in loadArray) + { + bool isDecimal = decimal.TryParse(load, out _); + if (!isDecimal) + { + return false; + } + } + cell.ErrorText = ""; + return true; + } + } +} diff --git a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs index 7f1e62098f..ea250c385d 100644 --- a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; +using XenAPI; namespace XenAdmin.Actions.NRPE { @@ -48,12 +49,12 @@ public class NRPEHostConfiguration : ICloneable public const string DEBUG_ENABLE = "1"; public const string DEBUG_DISABLE = "0"; - public const string SSL_LOGGING_ENABLE = "0xff"; + public const string SSL_LOGGING_ENABLE = "0x2f"; public const string SSL_LOGGING_DISABLE = "0x00"; public static readonly string ALLOW_HOSTS_PLACE_HOLDER = Messages.NRPE_ALLOW_HOSTS_PLACE_HOLDER; - private readonly Dictionary checkDict = new Dictionary(); + private Dictionary _checkDict = new Dictionary(); public bool EnableNRPE { get; set; } @@ -63,7 +64,17 @@ public class NRPEHostConfiguration : ICloneable public bool SslLogging { get; set; } - public Dictionary CheckDict => checkDict; + public Dictionary CheckDict => _checkDict; + + public RetrieveNRPEStatus Status { get; set; } + + public enum RetrieveNRPEStatus + { + Retrieving, + Successful, + Failed, + Unsupport + } public class Check { @@ -82,12 +93,12 @@ public Check(string name, string warningThreshold, string criticalThreshold) public void AddNRPECheck(Check checkItem) { - checkDict.Add(checkItem.Name, checkItem); + _checkDict.Add(checkItem.Name, checkItem); } public bool GetNRPECheck(string name, out Check check) { - return checkDict.TryGetValue(name, out check); + return _checkDict.TryGetValue(name, out check); } public object Clone() @@ -99,6 +110,12 @@ public object Clone() Debug = Debug, SslLogging = SslLogging }; + foreach (KeyValuePair kvp in _checkDict) + { + NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + cloned.AddNRPECheck(new Check(CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold)); + } + return cloned; } } diff --git a/XenModel/Actions/NRPE/NRPERetrieveAction.cs b/XenModel/Actions/NRPE/NRPERetrieveAction.cs new file mode 100644 index 0000000000..9c9b287aa8 --- /dev/null +++ b/XenModel/Actions/NRPE/NRPERetrieveAction.cs @@ -0,0 +1,163 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Threading; +using XenAPI; + + +namespace XenAdmin.Actions.NRPE +{ + public class NRPERetrieveAction : AsyncAction + { + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private readonly NRPEHostConfiguration _nrpeCurrentConfig; + private readonly Dictionary _checkGroupDictByName; + + private readonly IXenObject _clone; + + public NRPERetrieveAction(IXenObject host, NRPEHostConfiguration nrpeHostConfiguration, Dictionary checkGroupDictByName, bool suppressHistory) + : base(host.Connection, Messages.NRPE_ACTION_RETRIEVING, Messages.NRPE_ACTION_RETRIEVING, suppressHistory) + { + _clone = host; + _nrpeCurrentConfig = nrpeHostConfiguration; + _checkGroupDictByName = checkGroupDictByName; + } + + protected override void Run() + { + _nrpeCurrentConfig.Status = NRPEHostConfiguration.RetrieveNRPEStatus.Successful; + if (_clone is Pool p) + { + List hostList = p.Connection.Cache.Hosts.ToList(); + Host checkHost = hostList[0]; + try + { + Host.call_plugin(checkHost.Connection.Session, checkHost.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); + } + catch (Exception e) + { + log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}.", e.Message); + _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") ? + NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; + } + } + else + { + try + { + InitNRPEGeneralConfiguration(); + InitNRPEThreshold(); + } + catch (Exception e) + { + log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}.", e.Message); + _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") ? + NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; + } + } + } + + private void InitNRPEGeneralConfiguration() + { + string status = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_STATUS, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); + _nrpeCurrentConfig.EnableNRPE = status.Trim().Equals("active enabled"); + + string nrpeConfig = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); + + string[] nrpeConfigArray = nrpeConfig.Split('\n'); + foreach (string nrpeConfigItem in nrpeConfigArray) + { + if (nrpeConfigItem.Trim().StartsWith("allowed_hosts:")) + { + string allowHosts = nrpeConfigItem.Replace("allowed_hosts:", "").Trim(); + _nrpeCurrentConfig.AllowHosts = AllowHostsWithoutLocalAddress(allowHosts); + } + else if (nrpeConfigItem.Trim().StartsWith("debug:")) + { + string enableDebug = nrpeConfigItem.Replace("debug:", "").Trim(); + _nrpeCurrentConfig.Debug = enableDebug.Equals(NRPEHostConfiguration.DEBUG_ENABLE); + } + else if (nrpeConfigItem.Trim().StartsWith("ssl_logging:")) + { + string enableSslLogging = nrpeConfigItem.Replace("ssl_logging:", "").Trim(); + _nrpeCurrentConfig.SslLogging = enableSslLogging.Equals(NRPEHostConfiguration.SSL_LOGGING_ENABLE); + } + } + } + + private void InitNRPEThreshold() + { + string nrpeThreshold = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); + log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); + + string[] nrpeThresholdArray = nrpeThreshold.Split('\n'); + foreach (string nrpeThresholdItem in nrpeThresholdArray) + { + // Return string format for each line: check_cpu warning threshold - 50 critical threshold - 80 + string[] thresholdRtnArray = nrpeThresholdItem.Split(' '); + string checkName = thresholdRtnArray[0]; + if (_checkGroupDictByName.TryGetValue(thresholdRtnArray[0], out CheckGroup thresholdCheck)) + { + string warningThreshold = thresholdRtnArray[4]; + string criticalThreshold = thresholdRtnArray[8]; + thresholdCheck.UpdateThreshold(warningThreshold, criticalThreshold); + _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(checkName, warningThreshold, criticalThreshold)); + } + } + } + + private string AllowHostsWithoutLocalAddress(string allowHosts) + { + string UpdatedAllowHosts = ""; + string[] AllowHostArray = allowHosts.Split(','); + foreach (string allowHost in AllowHostArray) + { + if (!allowHost.Trim().Equals("127.0.0.1") && + !allowHost.Trim().Equals("::1")) + { + UpdatedAllowHosts += allowHost + ","; + } + } + return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : + UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + } + } +} diff --git a/XenModel/Actions/NRPE/NRPEUpdateAction.cs b/XenModel/Actions/NRPE/NRPEUpdateAction.cs index 05cb749dbe..f323b02431 100644 --- a/XenModel/Actions/NRPE/NRPEUpdateAction.cs +++ b/XenModel/Actions/NRPE/NRPEUpdateAction.cs @@ -39,22 +39,22 @@ public class NRPEUpdateAction : AsyncAction { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private readonly NRPEHostConfiguration NRPEOriginalConfig; // NRPE configuration fetched from host - private readonly NRPEHostConfiguration NRPEHostConfiguration; // NRPE configuration after user modified + private readonly NRPEHostConfiguration _nrpeOriginalConfig; // NRPE configuration fetched from host + private readonly NRPEHostConfiguration _nrpeHostConfiguration; // NRPE configuration after user modified - private readonly IXenObject Clone; + private readonly IXenObject _clone; public NRPEUpdateAction(IXenObject host, NRPEHostConfiguration nrpeHostConfiguration, NRPEHostConfiguration nrpeOriginalConfig, bool suppressHistory) - : base(host.Connection, Messages.ACTION_CHANGE_POWER_ON, Messages.NRPE_ACTION_CHANGING, suppressHistory) + : base(host.Connection, Messages.NRPE_ACTION_CHANGING, Messages.NRPE_ACTION_CHANGING, suppressHistory) { - Clone = host; - NRPEHostConfiguration = nrpeHostConfiguration; - NRPEOriginalConfig = nrpeOriginalConfig; + _clone = host; + _nrpeHostConfiguration = nrpeHostConfiguration; + _nrpeOriginalConfig = nrpeOriginalConfig; } protected override void Run() { - if (Clone is Host) + if (_clone is Host) { SetNRPEConfigureForHost(); } @@ -67,43 +67,43 @@ protected override void Run() private void SetNRPEConfigureForHost() { // Enable/Disable NRPE - if (!NRPEHostConfiguration.EnableNRPE == NRPEOriginalConfig.EnableNRPE) + if (!_nrpeHostConfiguration.EnableNRPE == _nrpeOriginalConfig.EnableNRPE) { - SetNRPEStatus(Clone, NRPEHostConfiguration.EnableNRPE); + SetNRPEStatus(_clone, _nrpeHostConfiguration.EnableNRPE); } - if (!NRPEHostConfiguration.EnableNRPE) // If disable, return + if (!_nrpeHostConfiguration.EnableNRPE) // If disable, return { return; } // NRPE General Configuration - if (!NRPEHostConfiguration.AllowHosts.Equals(NRPEOriginalConfig.AllowHosts) - || !NRPEHostConfiguration.Debug.Equals(NRPEOriginalConfig.Debug) - || !NRPEHostConfiguration.SslLogging.Equals(NRPEOriginalConfig.SslLogging)) + if (!_nrpeHostConfiguration.AllowHosts.Equals(_nrpeOriginalConfig.AllowHosts) + || !_nrpeHostConfiguration.Debug.Equals(_nrpeOriginalConfig.Debug) + || !_nrpeHostConfiguration.SslLogging.Equals(_nrpeOriginalConfig.SslLogging)) { - SetNRPEGeneralConfiguration(Clone, NRPEHostConfiguration.AllowHosts, NRPEHostConfiguration.Debug, NRPEHostConfiguration.SslLogging); + SetNRPEGeneralConfiguration(_clone, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, _nrpeHostConfiguration.SslLogging); } // NRPE Check Threshold - foreach (KeyValuePair kvp in NRPEHostConfiguration.CheckDict) + foreach (KeyValuePair kvp in _nrpeHostConfiguration.CheckDict) { NRPEHostConfiguration.Check CurrentCheck = kvp.Value; - NRPEOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); + _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); if (CurrentCheck != null && OriginalCheck != null && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) { - SetNRPEThreshold(Clone, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); + SetNRPEThreshold(_clone, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); } } - RestartNRPE(Clone); + RestartNRPE(_clone); } private void SetNRPEConfigureForPool() { List hostList = null; - if (Clone is Pool p) + if (_clone is Pool p) { hostList = p.Connection.Cache.Hosts.ToList(); } @@ -111,20 +111,20 @@ private void SetNRPEConfigureForPool() hostList.ForEach(host => { // Enable/Disable NRPE - SetNRPEStatus(host, NRPEHostConfiguration.EnableNRPE); - if (!NRPEHostConfiguration.EnableNRPE) // If disable, return + SetNRPEStatus(host, _nrpeHostConfiguration.EnableNRPE); + if (!_nrpeHostConfiguration.EnableNRPE) // If disable, return { return; } // NRPE General Configuration - SetNRPEGeneralConfiguration(host, NRPEHostConfiguration.AllowHosts, NRPEHostConfiguration.Debug, NRPEHostConfiguration.SslLogging); + SetNRPEGeneralConfiguration(host, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, _nrpeHostConfiguration.SslLogging); // NRPE Check Threshold - foreach (KeyValuePair kvp in NRPEHostConfiguration.CheckDict) + foreach (KeyValuePair kvp in _nrpeHostConfiguration.CheckDict) { NRPEHostConfiguration.Check CurrentCheck = kvp.Value; - NRPEOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); + _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); if (CurrentCheck != null) { SetNRPEThreshold(host, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); @@ -156,9 +156,9 @@ private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, boo NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, ConfigArgDict); log.InfoFormat("Execute nrpe {0}, allowed_hosts={1}, debug={2}, ssl_logging={3}, return: {4}", NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, - NRPEHostConfiguration.AllowHosts, - NRPEHostConfiguration.Debug, - NRPEHostConfiguration.SslLogging, + _nrpeHostConfiguration.AllowHosts, + _nrpeHostConfiguration.Debug, + _nrpeHostConfiguration.SslLogging, result); } diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index e387c153d0..92325ebca7 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29088,7 +29088,7 @@ public static string NRPE { } /// - /// Looks up a localized string similar to Changing NRPE configuration.... + /// Looks up a localized string similar to Changing NRPE configuration. /// public static string NRPE_ACTION_CHANGING { get { @@ -29096,6 +29096,15 @@ public static string NRPE_ACTION_CHANGING { } } + /// + /// Looks up a localized string similar to Retrieving NRPE configuration. + /// + public static string NRPE_ACTION_RETRIEVING { + get { + return ResourceManager.GetString("NRPE_ACTION_RETRIEVING", resourceCulture); + } + } + /// /// Looks up a localized string similar to NRPE service is active. /// @@ -29141,6 +29150,15 @@ public static string NRPE_ALLOW_HOSTS_PLACE_HOLDER { } } + /// + /// Looks up a localized string similar to Please remove duplicated address. + /// + public static string NRPE_ALLOW_HOSTS_SAME_ADDRESS { + get { + return ResourceManager.GetString("NRPE_ALLOW_HOSTS_SAME_ADDRESS", resourceCulture); + } + } + /// /// Looks up a localized string similar to NRPE batch configuration. /// @@ -29267,6 +29285,24 @@ public static string NRPE_INACTIVE { } } + /// + /// Looks up a localized string similar to Retrieve NRPE configuration failed, please check XenCenter logs.. + /// + public static string NRPE_RETRIEVE_FAILED { + get { + return ResourceManager.GetString("NRPE_RETRIEVE_FAILED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Retrieving NRPE configuration.... + /// + public static string NRPE_RETRIEVING_CONFIGURATION { + get { + return ResourceManager.GetString("NRPE_RETRIEVING_CONFIGURATION", resourceCulture); + } + } + /// /// Looks up a localized string similar to Threshold value should range from {0} to {1}.. /// @@ -29321,6 +29357,15 @@ public static string NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL { } } + /// + /// Looks up a localized string similar to Unsupport NRPE, please upgrade your XenServer version.. + /// + public static string NRPE_UNSUPPORT { + get { + return ResourceManager.GetString("NRPE_UNSUPPORT", resourceCulture); + } + } + /// /// Looks up a localized string similar to Number of snapshots to keep. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index b4418b67ce..6e390e156c 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10096,7 +10096,10 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE - Changing NRPE configuration... + Changing NRPE configuration + + + Retrieving NRPE configuration NRPE service is active @@ -10113,6 +10116,9 @@ When you configure an NFS storage repository, you simply provide the host name o Comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com + + Please remove duplicated address + NRPE batch configuration @@ -10155,6 +10161,12 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE service is inactive + + Retrieve NRPE configuration failed, please check XenCenter logs. + + + Retrieving NRPE configuration... + Threshold value should range from {0} to {1}. @@ -10173,6 +10185,9 @@ When you configure an NFS storage repository, you simply provide the host name o Warning threshold should be less than critical threshold. + + Unsupport NRPE, please upgrade your XenServer version. + Number of snapshots to keep @@ -15137,7 +15152,7 @@ Any disk in your VM's DVD drive will be ejected when installing {1}. Normal - + {0} recommends that you synchronize the selected pool(s) or standalone host(s) with the specified update channel as soon as possible to retrieve the latest available updates. diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 2850c5ca4d..117ab7806b 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -57,6 +57,7 @@ + @@ -88,6 +89,8 @@ + + From 5815dfa0863089f93b04b9b040f8060486af209e Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Thu, 12 Oct 2023 22:24:35 +0800 Subject: [PATCH 07/31] For pool, add a CheckBox for decide if to sync the NRPE configuration to all hosts. --- XenAdmin/Properties/AssemblyInfo.cs | 6 +- .../SettingsPanels/NRPEEditPage.Designer.cs | 90 +++---- XenAdmin/SettingsPanels/NRPEEditPage.cs | 219 ++++++++++-------- XenAdmin/SettingsPanels/NRPEEditPage.resx | 163 +++++++------ XenAdmin/XenAdmin.csproj | 4 +- 5 files changed, 265 insertions(+), 217 deletions(-) diff --git a/XenAdmin/Properties/AssemblyInfo.cs b/XenAdmin/Properties/AssemblyInfo.cs index 0b3ce02183..1e24ef8a49 100644 --- a/XenAdmin/Properties/AssemblyInfo.cs +++ b/XenAdmin/Properties/AssemblyInfo.cs @@ -35,10 +35,10 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("[XenCenter]")] -[assembly: AssemblyDescription("[XenCenter]")] +[assembly: AssemblyTitle("XenCenter")] +[assembly: AssemblyDescription("XenCenter")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("[XenCenter]")] +[assembly: AssemblyProduct("XenCenter")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index a3fcc3103b..6c41c02557 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -30,8 +30,7 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NRPEEditPage)); this.NRPETableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); - this.DescLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.BatchConfigurationCheckBox = new System.Windows.Forms.CheckBox(); this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); this.GeneralConfigureGroupBox = new System.Windows.Forms.GroupBox(); this.GeneralConfigTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); @@ -39,19 +38,21 @@ private void InitializeComponent() this.AllowHostsTextBox = new System.Windows.Forms.TextBox(); this.DebugLogCheckBox = new System.Windows.Forms.CheckBox(); this.SslDebugLogCheckBox = new System.Windows.Forms.CheckBox(); + this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); + this.RetrieveNRPELabel = new System.Windows.Forms.Label(); + this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); + this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.DescLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); this.CheckDataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); - this.RetrieveNRPELabel = new System.Windows.Forms.Label(); - this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); this.NRPETableLayoutPanel.SuspendLayout(); this.GeneralConfigureGroupBox.SuspendLayout(); this.GeneralConfigTableLayoutPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); this.RetrieveNRPEPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); this.SuspendLayout(); // // NRPETableLayoutPanel @@ -59,21 +60,19 @@ private void InitializeComponent() resources.ApplyResources(this.NRPETableLayoutPanel, "NRPETableLayoutPanel"); this.NRPETableLayoutPanel.Controls.Add(this.DescLabelPool, 0, 0); this.NRPETableLayoutPanel.Controls.Add(this.DescLabelHost, 0, 1); - this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 2); - this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 3); - this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 4); - this.NRPETableLayoutPanel.Controls.Add(this.RetrieveNRPEPanel, 0, 5); + this.NRPETableLayoutPanel.Controls.Add(this.BatchConfigurationCheckBox, 0, 2); + this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 3); + this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 4); + this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 5); + this.NRPETableLayoutPanel.Controls.Add(this.RetrieveNRPEPanel, 0, 6); this.NRPETableLayoutPanel.Name = "NRPETableLayoutPanel"; // - // DescLabelPool - // - resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); - this.DescLabelPool.Name = "DescLabelPool"; - // - // DescLabelHost + // BatchConfigurationCheckBox // - resources.ApplyResources(this.DescLabelHost, "DescLabelHost"); - this.DescLabelHost.Name = "DescLabelHost"; + resources.ApplyResources(this.BatchConfigurationCheckBox, "BatchConfigurationCheckBox"); + this.BatchConfigurationCheckBox.Name = "BatchConfigurationCheckBox"; + this.BatchConfigurationCheckBox.UseVisualStyleBackColor = true; + this.BatchConfigurationCheckBox.CheckedChanged += new System.EventHandler(this.BatchConfigurationCheckBox_CheckedChanged); // // EnableNRPECheckBox // @@ -122,6 +121,34 @@ private void InitializeComponent() this.SslDebugLogCheckBox.Name = "SslDebugLogCheckBox"; this.SslDebugLogCheckBox.UseVisualStyleBackColor = true; // + // RetrieveNRPEPanel + // + resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPELabel, 1, 0); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPEPicture, 0, 0); + this.RetrieveNRPEPanel.Name = "RetrieveNRPEPanel"; + // + // RetrieveNRPELabel + // + resources.ApplyResources(this.RetrieveNRPELabel, "RetrieveNRPELabel"); + this.RetrieveNRPELabel.Name = "RetrieveNRPELabel"; + // + // RetrieveNRPEPicture + // + resources.ApplyResources(this.RetrieveNRPEPicture, "RetrieveNRPEPicture"); + this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; + this.RetrieveNRPEPicture.TabStop = false; + // + // DescLabelPool + // + resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); + this.DescLabelPool.Name = "DescLabelPool"; + // + // DescLabelHost + // + resources.ApplyResources(this.DescLabelHost, "DescLabelHost"); + this.DescLabelHost.Name = "DescLabelHost"; + // // CheckDataGridView // this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; @@ -141,41 +168,23 @@ private void InitializeComponent() // // CheckColumn // - this.CheckColumn.FillWeight = 40F; + this.CheckColumn.FillWeight = 15.57632F; resources.ApplyResources(this.CheckColumn, "CheckColumn"); this.CheckColumn.Name = "CheckColumn"; this.CheckColumn.ReadOnly = true; // // WarningThresholdColumn // - this.WarningThresholdColumn.FillWeight = 30F; + this.WarningThresholdColumn.FillWeight = 42.21184F; resources.ApplyResources(this.WarningThresholdColumn, "WarningThresholdColumn"); this.WarningThresholdColumn.Name = "WarningThresholdColumn"; // // CriticalThresholdColumn // - this.CriticalThresholdColumn.FillWeight = 30F; + this.CriticalThresholdColumn.FillWeight = 42.21184F; resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; // - // RetrieveNRPEPanel - // - resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); - this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPELabel, 1, 0); - this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPEPicture, 0, 0); - this.RetrieveNRPEPanel.Name = "RetrieveNRPEPanel"; - // - // RetrieveNRPELabel - // - resources.ApplyResources(this.RetrieveNRPELabel, "RetrieveNRPELabel"); - this.RetrieveNRPELabel.Name = "RetrieveNRPELabel"; - // - // RetrieveNRPEPicture - // - resources.ApplyResources(this.RetrieveNRPEPicture, "RetrieveNRPEPicture"); - this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; - this.RetrieveNRPEPicture.TabStop = false; - // // NRPEEditPage // resources.ApplyResources(this, "$this"); @@ -188,9 +197,9 @@ private void InitializeComponent() this.GeneralConfigureGroupBox.PerformLayout(); this.GeneralConfigTableLayoutPanel.ResumeLayout(false); this.GeneralConfigTableLayoutPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); this.RetrieveNRPEPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); this.ResumeLayout(false); } @@ -213,6 +222,7 @@ private void InitializeComponent() private System.Windows.Forms.Label RetrieveNRPELabel; private System.Windows.Forms.TableLayoutPanel RetrieveNRPEPanel; private System.Windows.Forms.PictureBox RetrieveNRPEPicture; + private System.Windows.Forms.CheckBox BatchConfigurationCheckBox; } } \ No newline at end of file diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index 8193664289..191ab0f6fa 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -96,6 +96,7 @@ public NRPEEditPage() _checkGroupDictByLabel.Add(checkGroup.NameCell.Value.ToString(), checkGroup); } + AllowHostsTextBox.Text = NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER; AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); AllowHostsTextBox.GotFocus += AllowHostsTextBox_GotFocus; AllowHostsTextBox.LostFocus += AllowHostsTextBox_LostFocus; @@ -158,15 +159,13 @@ public bool HasChanged { get { - UpdateCurrentNRPEConfiguration(); - if (_isHost) - { - return IsNRPEConfigurationChanged(); - } - else + if (_isHost && IsNRPEConfigurationChanged() || + !_isHost && BatchConfigurationCheckBox.Checked) { + UpdateCurrentNRPEConfiguration(); return true; } + return false; } } @@ -235,6 +234,7 @@ public void SetXenObjects(IXenObject orig, IXenObject clone) DescLabelHost.Visible = _isHost; DescLabelPool.Visible = !_isHost; + BatchConfigurationCheckBox.Visible = !_isHost; UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus.Retrieving); DisableAllComponent(); @@ -252,10 +252,16 @@ private void UpdateRetrieveStatus() { if (_nrpeOriginalConfig.Status == NRPEHostConfiguration.RetrieveNRPEStatus.Successful) { - AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? - Color.FromKnownColor(KnownColor.ControlDark) : Color.FromKnownColor(KnownColor.ControlText); - UpdateOtherComponentBasedEnableNRPECheckBox(); - UpdateComponentBasedConfiguration(); + if (_isHost) + { + EnableNRPECheckBox.Enabled = true; + UpdateComponentValueBasedConfiguration(); + UpdateComponentStatusBasedEnableNRPECheckBox(); + } + else + { + BatchConfigurationCheckBox.Enabled = true; + } } UpdateRetrievingNRPETip(_nrpeOriginalConfig.Status); } @@ -291,96 +297,40 @@ private void UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus st private void DisableAllComponent() { - EnableNRPECheckBox.Enabled = false; - GeneralConfigureGroupBox.Enabled = false; - CheckDataGridView.Enabled = false; - } - - private bool IsAllowHostsValid() - { - _invalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; - _invalidParamToolTip.Tag = AllowHostsTextBox; - CheckDataGridView.ShowCellToolTips = true; - - string str = AllowHostsTextBox.Text; - if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) - { - _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_EMPTY_ERROR; - return false; - } - - string[] hostArray = str.Split(','); - for ( int i = 0; i < hostArray.Length; i++ ) - { - if (!REGEX_IPV4.Match(hostArray[i].Trim()).Success && - !REGEX_IPV4_CIDR.Match(hostArray[i].Trim()).Success && - !REGEX_DOMAIN.Match(hostArray[i].Trim()).Success) - { - _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; - return false; - } - for ( int j = 0; j < i; j++ ) - { - if (hostArray[i].Trim().Equals(hostArray[j].Trim())) - { - _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_SAME_ADDRESS; - return false; - } - } - } - foreach (string host in hostArray) - { - if (!REGEX_IPV4.Match(host.Trim()).Success && - !REGEX_IPV4_CIDR.Match(host.Trim()).Success && - !REGEX_DOMAIN.Match(host.Trim()).Success) - { - _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; - return false; - } - } - CheckDataGridView.ShowCellToolTips = false; - return true; - } - - private string AllowHostsWithoutLocalAddress(string allowHosts) - { - string UpdatedAllowHosts = ""; - string[] AllowHostArray = allowHosts.Split(','); - foreach (string allowHost in AllowHostArray) - { - if (!allowHost.Trim().Equals("127.0.0.1") && - !allowHost.Trim().Equals("::1")) - { - UpdatedAllowHosts += allowHost + ","; - } - } - return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : - UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); - } - - private void UpdateOtherComponentBasedEnableNRPECheckBox() - { - GeneralConfigureGroupBox.Enabled = EnableNRPECheckBox.Checked; - UpdateCheckDataGridViewAvailableStatus(); - } - - private void UpdateComponentBasedConfiguration() - { - EnableNRPECheckBox.Enabled = true; - EnableNRPECheckBox.Checked = _nrpeOriginalConfig.EnableNRPE; - AllowHostsTextBox.Text = AllowHostsWithoutLocalAddress(_nrpeOriginalConfig.AllowHosts); - AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? - Color.FromKnownColor(KnownColor.ControlDark) : AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - DebugLogCheckBox.Checked = _nrpeOriginalConfig.Debug; - SslDebugLogCheckBox.Checked = _nrpeOriginalConfig.SslLogging; - UpdateCheckDataGridViewAvailableStatus(); - } - - private void UpdateCheckDataGridViewAvailableStatus() - { - CheckDataGridView.Enabled = EnableNRPECheckBox.Checked; - CheckDataGridView.DefaultCellStyle.BackColor = EnableNRPECheckBox.Checked ? - Color.FromKnownColor(KnownColor.Window) : Color.FromKnownColor(KnownColor.Control); + EnableNRPECheckBox.Enabled = false; + GeneralConfigureGroupBox.Enabled = false; + CheckDataGridView.Enabled = false; + } + + private void UpdateComponentValueBasedConfiguration() + { + EnableNRPECheckBox.Checked = _nrpeOriginalConfig.EnableNRPE; + AllowHostsTextBox.Text = AllowHostsWithoutLocalAddress(_nrpeOriginalConfig.AllowHosts); + AllowHostsTextBox.ForeColor = AllowHostsTextBox.Text.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? + Color.FromKnownColor(KnownColor.ControlDark) : AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + DebugLogCheckBox.Checked = _nrpeOriginalConfig.Debug; + SslDebugLogCheckBox.Checked = _nrpeOriginalConfig.SslLogging; + } + + private void UpdateComponentStatusBasedBatchConfigurationCheckBox() + { + if (BatchConfigurationCheckBox.Checked) + { + EnableNRPECheckBox.Enabled = true; + UpdateComponentStatusBasedEnableNRPECheckBox(); + } + else + { + DisableAllComponent(); + } + } + + private void UpdateComponentStatusBasedEnableNRPECheckBox() + { + GeneralConfigureGroupBox.Enabled = EnableNRPECheckBox.Checked; + CheckDataGridView.Enabled = EnableNRPECheckBox.Checked; + CheckDataGridView.DefaultCellStyle.BackColor = EnableNRPECheckBox.Checked ? + Color.FromKnownColor(KnownColor.Window) : Color.FromKnownColor(KnownColor.Control); if (_isHost) { foreach (var checkGroup in _checkGroupList) @@ -399,6 +349,68 @@ private void UpdateCheckDataGridViewAvailableStatus() } } + private bool IsAllowHostsValid() + { + _invalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; + _invalidParamToolTip.Tag = AllowHostsTextBox; + CheckDataGridView.ShowCellToolTips = true; + + string str = AllowHostsTextBox.Text; + if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_EMPTY_ERROR; + return false; + } + + string[] hostArray = str.Split(','); + for ( int i = 0; i < hostArray.Length; i++ ) + { + if (!REGEX_IPV4.Match(hostArray[i].Trim()).Success && + !REGEX_IPV4_CIDR.Match(hostArray[i].Trim()).Success && + !REGEX_DOMAIN.Match(hostArray[i].Trim()).Success) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; + return false; + } + for ( int j = 0; j < i; j++ ) + { + if (hostArray[i].Trim().Equals(hostArray[j].Trim())) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_SAME_ADDRESS; + return false; + } + } + } + foreach (string host in hostArray) + { + if (!REGEX_IPV4.Match(host.Trim()).Success && + !REGEX_IPV4_CIDR.Match(host.Trim()).Success && + !REGEX_DOMAIN.Match(host.Trim()).Success) + { + _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; + return false; + } + } + CheckDataGridView.ShowCellToolTips = false; + return true; + } + + private string AllowHostsWithoutLocalAddress(string allowHosts) + { + string UpdatedAllowHosts = ""; + string[] AllowHostArray = allowHosts.Split(','); + foreach (string allowHost in AllowHostArray) + { + if (!allowHost.Trim().Equals("127.0.0.1") && + !allowHost.Trim().Equals("::1")) + { + UpdatedAllowHosts += allowHost + ","; + } + } + return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : + UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + } + private bool IsNRPEConfigurationChanged() { if (_nrpeCurrentConfig.EnableNRPE != _nrpeOriginalConfig.EnableNRPE || @@ -442,9 +454,14 @@ private void UpdateCurrentNRPEConfiguration() } } + private void BatchConfigurationCheckBox_CheckedChanged(object sender, EventArgs e) + { + UpdateComponentStatusBasedBatchConfigurationCheckBox(); + } + private void EnableNRPECheckBox_CheckedChanged(object sender, EventArgs e) { - UpdateOtherComponentBasedEnableNRPECheckBox(); + UpdateComponentStatusBasedEnableNRPECheckBox(); } private void AllowHostsTextBox_GotFocus(object sender, EventArgs e) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx index b8734a0554..bfbbd26f35 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.resx +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -133,13 +133,13 @@ - 4, 0 + 3, 0 - 4, 0, 4, 15 + 3, 0, 3, 10 - 967, 39 + 644, 39 0 @@ -152,7 +152,7 @@ This page does not offer an overview of the NRPE configuration and metric thresh DescLabelPool - XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -170,13 +170,13 @@ This page does not offer an overview of the NRPE configuration and metric thresh NoControl - 4, 54 + 3, 49 - 4, 0, 4, 15 + 3, 0, 3, 10 - 967, 26 + 644, 26 1 @@ -189,7 +189,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s DescLabelHost - XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -197,6 +197,42 @@ Use this page to review and modify the NRPE configuration and metric threshold s 1 + + True + + + NoControl + + + 3, 88 + + + 3, 3, 3, 8 + + + 3, 0, 0, 0 + + + 171, 17 + + + 7 + + + Sync &Configuration to all hosts + + + BatchConfigurationCheckBox + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + NRPETableLayoutPanel + + + 2 + True @@ -204,16 +240,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 99 + 3, 116 - 4, 4, 4, 12 + 3, 3, 3, 8 - 4, 0, 0, 0 + 3, 0, 0, 0 - 103, 21 + 95, 17 2 @@ -231,7 +267,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 2 + 3 True @@ -252,10 +288,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 7 - - - 4, 0, 4, 0 + 3, 6 96, 13 @@ -282,13 +315,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s Left, Right - 108, 4 - - - 4, 4, 4, 4 + 105, 3 - 847, 20 + 530, 20 1 @@ -312,16 +342,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 32 - - - 4, 4, 4, 4 + 3, 29 - 4, 0, 0, 0 + 3, 0, 0, 0 - 219, 21 + 211, 17 2 @@ -348,16 +375,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 61 - - - 4, 4, 4, 4 + 3, 52 - 4, 0, 0, 0 + 3, 0, 0, 0 - 189, 21 + 181, 17 3 @@ -381,16 +405,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s Top - 4, 17 - - - 4, 4, 4, 4 + 3, 16 3 - 959, 86 + 638, 72 0 @@ -408,22 +429,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,30" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,20" /></TableLayoutSettings> Fill - 4, 136 + 3, 144 - 4, 4, 4, 15 + 3, 3, 3, 10 - 4, 4, 4, 0 + 3, 3, 3, 0 - 967, 150 + 644, 100 3 @@ -441,7 +462,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 3 + 4 34 @@ -474,16 +495,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s Fill - 4, 305 - - - 4, 4, 4, 4 + 3, 257 62 - 967, 450 + 644, 248 4 @@ -492,13 +510,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s CheckDataGridView - XenAdmin.Controls.DataGridViewEx.DataGridViewEx, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.DataGridViewEx.DataGridViewEx, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel - 4 + 5 True @@ -513,13 +531,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 35, 0 - - - 4, 0, 4, 0 + 24, 0 - 930, 31 + 619, 5 5 @@ -542,11 +557,17 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 + + NoControl + - 3, 3 + 2, 2 + + + 2, 2, 2, 2 - 25, 25 + 17, 1 6 @@ -564,13 +585,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s 1 - 3, 762 + 2, 510 + + + 2, 2, 2, 2 1 - 969, 31 + 646, 5 6 @@ -585,7 +609,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 5 + 6 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="RetrieveNRPELabel" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="RetrieveNRPEPicture" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="Percent,100" /></TableLayoutSettings> @@ -597,13 +621,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0, 0 - 4, 15, 4, 0 + 3, 10, 3, 0 - 7 + 8 - 975, 806 + 650, 537 0 @@ -621,22 +645,19 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,10" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="BatchConfigurationCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="6" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,20" /></TableLayoutSettings> True - 144, 144 + 96, 96 True - - 4, 4, 4, 4 - - 975, 806 + 650, 537 CheckColumn diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index 26125ed37f..0e1b7504d9 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -9,7 +9,7 @@ WinExe Properties XenAdmin - [XenCenter] + XenCenter ..\Branding\Images\AppIcon.ico v4.8 publish\ @@ -6808,4 +6808,4 @@ copy "$(ProjectDir)\ReportViewer\resource_report.rdlc" "$(TargetDir)" - \ No newline at end of file + From aac73932cee6616a61b50e3494fe9a911fd91552 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Mon, 16 Oct 2023 16:59:33 +0800 Subject: [PATCH 08/31] All the configurations of host in a pool are the same. Fix some review comments. --- XenAdmin/Dialogs/PropertiesDialog.cs | 2 +- XenAdmin/Properties/AssemblyInfo.cs | 6 +- .../SettingsPanels/NRPEEditPage.Designer.cs | 80 ++++----- XenAdmin/SettingsPanels/NRPEEditPage.cs | 163 ++--------------- XenAdmin/SettingsPanels/NRPEEditPage.resx | 165 ++++++++---------- .../Actions/NRPE/NRPEHostConfiguration.cs | 25 ++- XenModel/Actions/NRPE/NRPERetrieveAction.cs | 46 ++--- XenModel/Actions/NRPE/NRPEUpdateAction.cs | 42 +---- 8 files changed, 178 insertions(+), 351 deletions(-) diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index 8c6f9de77d..1af7923bf1 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -318,7 +318,7 @@ private void Build() dialog.ShowDialog(Program.MainWindow); } } - if ((isHost || isPool) && + if (isPoolOrStandalone && (connection.Session.IsLocalSuperuser || connection.Session.Roles.Any(r => r.name_label == Role.MR_ROLE_POOL_ADMIN))) { NRPEEditPage = new NRPEEditPage(); diff --git a/XenAdmin/Properties/AssemblyInfo.cs b/XenAdmin/Properties/AssemblyInfo.cs index 1e24ef8a49..0b3ce02183 100644 --- a/XenAdmin/Properties/AssemblyInfo.cs +++ b/XenAdmin/Properties/AssemblyInfo.cs @@ -35,10 +35,10 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("XenCenter")] -[assembly: AssemblyDescription("XenCenter")] +[assembly: AssemblyTitle("[XenCenter]")] +[assembly: AssemblyDescription("[XenCenter]")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("XenCenter")] +[assembly: AssemblyProduct("[XenCenter]")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index 6c41c02557..a619e79ac5 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -30,7 +30,8 @@ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NRPEEditPage)); this.NRPETableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - this.BatchConfigurationCheckBox = new System.Windows.Forms.CheckBox(); + this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); + this.DescLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); this.EnableNRPECheckBox = new System.Windows.Forms.CheckBox(); this.GeneralConfigureGroupBox = new System.Windows.Forms.GroupBox(); this.GeneralConfigTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); @@ -38,21 +39,19 @@ private void InitializeComponent() this.AllowHostsTextBox = new System.Windows.Forms.TextBox(); this.DebugLogCheckBox = new System.Windows.Forms.CheckBox(); this.SslDebugLogCheckBox = new System.Windows.Forms.CheckBox(); + this.CheckDataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); this.RetrieveNRPELabel = new System.Windows.Forms.Label(); this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); - this.DescLabelPool = new XenAdmin.Controls.Common.AutoHeightLabel(); - this.DescLabelHost = new XenAdmin.Controls.Common.AutoHeightLabel(); - this.CheckDataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NRPETableLayoutPanel.SuspendLayout(); this.GeneralConfigureGroupBox.SuspendLayout(); this.GeneralConfigTableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); this.RetrieveNRPEPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).BeginInit(); this.SuspendLayout(); // // NRPETableLayoutPanel @@ -60,19 +59,21 @@ private void InitializeComponent() resources.ApplyResources(this.NRPETableLayoutPanel, "NRPETableLayoutPanel"); this.NRPETableLayoutPanel.Controls.Add(this.DescLabelPool, 0, 0); this.NRPETableLayoutPanel.Controls.Add(this.DescLabelHost, 0, 1); - this.NRPETableLayoutPanel.Controls.Add(this.BatchConfigurationCheckBox, 0, 2); this.NRPETableLayoutPanel.Controls.Add(this.EnableNRPECheckBox, 0, 3); this.NRPETableLayoutPanel.Controls.Add(this.GeneralConfigureGroupBox, 0, 4); this.NRPETableLayoutPanel.Controls.Add(this.CheckDataGridView, 0, 5); this.NRPETableLayoutPanel.Controls.Add(this.RetrieveNRPEPanel, 0, 6); this.NRPETableLayoutPanel.Name = "NRPETableLayoutPanel"; // - // BatchConfigurationCheckBox + // DescLabelPool + // + resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); + this.DescLabelPool.Name = "DescLabelPool"; // - resources.ApplyResources(this.BatchConfigurationCheckBox, "BatchConfigurationCheckBox"); - this.BatchConfigurationCheckBox.Name = "BatchConfigurationCheckBox"; - this.BatchConfigurationCheckBox.UseVisualStyleBackColor = true; - this.BatchConfigurationCheckBox.CheckedChanged += new System.EventHandler(this.BatchConfigurationCheckBox_CheckedChanged); + // DescLabelHost + // + resources.ApplyResources(this.DescLabelHost, "DescLabelHost"); + this.DescLabelHost.Name = "DescLabelHost"; // // EnableNRPECheckBox // @@ -121,6 +122,21 @@ private void InitializeComponent() this.SslDebugLogCheckBox.Name = "SslDebugLogCheckBox"; this.SslDebugLogCheckBox.UseVisualStyleBackColor = true; // + // CheckDataGridView + // + this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.CheckDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); + this.CheckDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.CheckColumn, + this.WarningThresholdColumn, + this.CriticalThresholdColumn}); + this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; + this.CheckDataGridView.Name = "CheckDataGridView"; + this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; + this.CheckDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; + // // RetrieveNRPEPanel // resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); @@ -139,49 +155,22 @@ private void InitializeComponent() this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; this.RetrieveNRPEPicture.TabStop = false; // - // DescLabelPool - // - resources.ApplyResources(this.DescLabelPool, "DescLabelPool"); - this.DescLabelPool.Name = "DescLabelPool"; - // - // DescLabelHost - // - resources.ApplyResources(this.DescLabelHost, "DescLabelHost"); - this.DescLabelHost.Name = "DescLabelHost"; - // - // CheckDataGridView - // - this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.CheckDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; - resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); - this.CheckDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; - this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { - this.CheckColumn, - this.WarningThresholdColumn, - this.CriticalThresholdColumn}); - this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; - this.CheckDataGridView.Name = "CheckDataGridView"; - this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; - this.CheckDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; - this.CheckDataGridView.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.CheckDataGridView_BeginEdit); - this.CheckDataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.CheckDataGridView_EndEdit); - // // CheckColumn // - this.CheckColumn.FillWeight = 15.57632F; + this.CheckColumn.FillWeight = 40F; resources.ApplyResources(this.CheckColumn, "CheckColumn"); this.CheckColumn.Name = "CheckColumn"; this.CheckColumn.ReadOnly = true; // // WarningThresholdColumn // - this.WarningThresholdColumn.FillWeight = 42.21184F; + this.WarningThresholdColumn.FillWeight = 30F; resources.ApplyResources(this.WarningThresholdColumn, "WarningThresholdColumn"); this.WarningThresholdColumn.Name = "WarningThresholdColumn"; // // CriticalThresholdColumn // - this.CriticalThresholdColumn.FillWeight = 42.21184F; + this.CriticalThresholdColumn.FillWeight = 30F; resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; // @@ -197,9 +186,9 @@ private void InitializeComponent() this.GeneralConfigureGroupBox.PerformLayout(); this.GeneralConfigTableLayoutPanel.ResumeLayout(false); this.GeneralConfigTableLayoutPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); this.RetrieveNRPEPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.RetrieveNRPEPicture)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.CheckDataGridView)).EndInit(); this.ResumeLayout(false); } @@ -216,13 +205,12 @@ private void InitializeComponent() private System.Windows.Forms.CheckBox SslDebugLogCheckBox; private Controls.DataGridViewEx.DataGridViewEx CheckDataGridView; private Controls.Common.AutoHeightLabel DescLabelHost; - private System.Windows.Forms.DataGridViewTextBoxColumn CheckColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn WarningThresholdColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn CriticalThresholdColumn; private System.Windows.Forms.Label RetrieveNRPELabel; private System.Windows.Forms.TableLayoutPanel RetrieveNRPEPanel; private System.Windows.Forms.PictureBox RetrieveNRPEPicture; - private System.Windows.Forms.CheckBox BatchConfigurationCheckBox; + private System.Windows.Forms.DataGridViewTextBoxColumn CheckColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn WarningThresholdColumn; + private System.Windows.Forms.DataGridViewTextBoxColumn CriticalThresholdColumn; } } \ No newline at end of file diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index 191ab0f6fa..ffbde99d92 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -37,14 +37,11 @@ using XenAdmin.Core; using XenAdmin.Actions.NRPE; using XenAPI; -using System.Linq; namespace XenAdmin.SettingsPanels { public partial class NRPEEditPage : UserControl, IEditPage { - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); @@ -108,21 +105,13 @@ public NRPEEditPage() ToolTipTitle = Messages.INVALID_PARAMETER, Tag = AllowHostsTextBox }; - DisableAllComponent(); } public string SubText { get { - if (_isHost) - { - return Messages.NRPE_EDIT_PAGE_TEXT; - } - else - { - return Messages.NRPE_BATCH_CONFIGURATION; - } + return Messages.NRPE_EDIT_PAGE_TEXT; } } @@ -159,10 +148,9 @@ public bool HasChanged { get { - if (_isHost && IsNRPEConfigurationChanged() || - !_isHost && BatchConfigurationCheckBox.Checked) + UpdateCurrentNRPEConfiguration(); + if (!_nrpeCurrentConfig.Equals(_nrpeOriginalConfig)) { - UpdateCurrentNRPEConfiguration(); return true; } return false; @@ -198,35 +186,6 @@ public AsyncAction SaveSettings() return new NRPEUpdateAction(_clone, _nrpeCurrentConfig, _nrpeOriginalConfig, true); } - public bool IsNRPEAvailable(IXenObject clone) - { - IXenObject checkHost; - if (clone is Host h) - { - checkHost = h; - } - else if (clone is Pool p) - { - List hostList = p.Connection.Cache.Hosts.ToList(); - checkHost = hostList[0]; - } - else - { - return false; - } - try - { - Host.call_plugin(checkHost.Connection.Session, checkHost.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); - } - catch (Exception e) - { - log.InfoFormat("Execute NRPE plugin failed, failed reason: {0}. It may not support NRPE.", e.Message); - return false; - } - return true; - } - public void SetXenObjects(IXenObject orig, IXenObject clone) { _clone = clone; @@ -234,7 +193,6 @@ public void SetXenObjects(IXenObject orig, IXenObject clone) DescLabelHost.Visible = _isHost; DescLabelPool.Visible = !_isHost; - BatchConfigurationCheckBox.Visible = !_isHost; UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus.Retrieving); DisableAllComponent(); @@ -252,16 +210,9 @@ private void UpdateRetrieveStatus() { if (_nrpeOriginalConfig.Status == NRPEHostConfiguration.RetrieveNRPEStatus.Successful) { - if (_isHost) - { - EnableNRPECheckBox.Enabled = true; - UpdateComponentValueBasedConfiguration(); - UpdateComponentStatusBasedEnableNRPECheckBox(); - } - else - { - BatchConfigurationCheckBox.Enabled = true; - } + EnableNRPECheckBox.Enabled = true; + UpdateComponentValueBasedConfiguration(); + UpdateComponentStatusBasedEnableNRPECheckBox(); } UpdateRetrievingNRPETip(_nrpeOriginalConfig.Status); } @@ -312,39 +263,24 @@ private void UpdateComponentValueBasedConfiguration() SslDebugLogCheckBox.Checked = _nrpeOriginalConfig.SslLogging; } - private void UpdateComponentStatusBasedBatchConfigurationCheckBox() - { - if (BatchConfigurationCheckBox.Checked) - { - EnableNRPECheckBox.Enabled = true; - UpdateComponentStatusBasedEnableNRPECheckBox(); - } - else - { - DisableAllComponent(); - } - } - private void UpdateComponentStatusBasedEnableNRPECheckBox() { GeneralConfigureGroupBox.Enabled = EnableNRPECheckBox.Checked; CheckDataGridView.Enabled = EnableNRPECheckBox.Checked; + CheckDataGridView.ScrollBars = ScrollBars.Both; CheckDataGridView.DefaultCellStyle.BackColor = EnableNRPECheckBox.Checked ? Color.FromKnownColor(KnownColor.Window) : Color.FromKnownColor(KnownColor.Control); - if (_isHost) + foreach (var checkGroup in _checkGroupList) { - foreach (var checkGroup in _checkGroupList) + if (EnableNRPECheckBox.Checked) { - if (EnableNRPECheckBox.Checked) - { - checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - } - else - { - checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - } + checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + else + { + checkGroup.WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); } } } @@ -411,29 +347,6 @@ private string AllowHostsWithoutLocalAddress(string allowHosts) UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); } - private bool IsNRPEConfigurationChanged() - { - if (_nrpeCurrentConfig.EnableNRPE != _nrpeOriginalConfig.EnableNRPE || - !_nrpeCurrentConfig.AllowHosts.Equals(_nrpeOriginalConfig.AllowHosts) || - _nrpeCurrentConfig.Debug != _nrpeOriginalConfig.Debug || - _nrpeCurrentConfig.SslLogging != _nrpeOriginalConfig.SslLogging) - { - return true; - } - foreach (KeyValuePair kvp in _nrpeCurrentConfig.CheckDict) - { - NRPEHostConfiguration.Check CurrentCheck = kvp.Value; - _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); - if (CurrentCheck != null && OriginalCheck != null - && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) - || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) - { - return true; - } - } - return false; - } - private void UpdateCurrentNRPEConfiguration() { _nrpeCurrentConfig = new NRPEHostConfiguration @@ -445,20 +358,11 @@ private void UpdateCurrentNRPEConfiguration() }; foreach (KeyValuePair item in _checkGroupDictByName) { - if (item.Value.WarningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) - && item.Value.CriticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) - { - _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, - item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); - } + _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, + item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); } } - private void BatchConfigurationCheckBox_CheckedChanged(object sender, EventArgs e) - { - UpdateComponentStatusBasedBatchConfigurationCheckBox(); - } - private void EnableNRPECheckBox_CheckedChanged(object sender, EventArgs e) { UpdateComponentStatusBasedEnableNRPECheckBox(); @@ -481,36 +385,5 @@ private void AllowHostsTextBox_LostFocus(object sender, EventArgs e) AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); } } - - private void CheckDataGridView_BeginEdit(object sender, DataGridViewCellCancelEventArgs e) - { - DataGridViewCell currentCell = CheckDataGridView.CurrentRow?.Cells[e.ColumnIndex]; - - if (currentCell != null && !_isHost && currentCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) - { - currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - currentCell.Value = ""; - } - } - - private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs e) - { - DataGridViewCell currentCell = CheckDataGridView.CurrentRow?.Cells[e.ColumnIndex]; - - if (currentCell != null &&!_isHost && currentCell.Value.ToString().Trim().Equals("")) - { - currentCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - _checkGroupDictByLabel.TryGetValue(CheckDataGridView.CurrentRow.Cells[0].Value.ToString(), out CheckGroup checkGroup); - - if (checkGroup != null) - { - if (currentCell.ColumnIndex == WarningThresholdColumn.Index) - currentCell.Value = checkGroup.WarningThresholdDefault; - else if (currentCell.ColumnIndex == CriticalThresholdColumn.Index) - currentCell.Value = checkGroup.CriticalThresholdDefault; - } - _nrpeOriginalConfig.CheckDict.TryGetValue(checkGroup.Name, out NRPEHostConfiguration.Check check); - } - } } } diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx index bfbbd26f35..3250d8794e 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.resx +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -133,26 +133,26 @@ - 3, 0 + 4, 0 - 3, 0, 3, 10 + 4, 0, 4, 15 - 644, 39 + 967, 40 0 Nagios Remote Plugin Executor (NRPE) allows you to monitor remotely resource metrics on the servers of your pool. -This page does not offer an overview of the NRPE configuration and metric threshold settings of the pool servers. Use it only to apply your chosen configuration and threshold settings to all servers in the pool. +Use this page to review and modify the NRPE configuration and metric threshold settings used for this pool. DescLabelPool - XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -170,13 +170,13 @@ This page does not offer an overview of the NRPE configuration and metric thresh NoControl - 3, 49 + 4, 55 - 3, 0, 3, 10 + 4, 0, 4, 15 - 644, 26 + 967, 40 1 @@ -189,7 +189,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s DescLabelHost - XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -197,42 +197,6 @@ Use this page to review and modify the NRPE configuration and metric threshold s 1 - - True - - - NoControl - - - 3, 88 - - - 3, 3, 3, 8 - - - 3, 0, 0, 0 - - - 171, 17 - - - 7 - - - Sync &Configuration to all hosts - - - BatchConfigurationCheckBox - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - NRPETableLayoutPanel - - - 2 - True @@ -240,16 +204,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 116 + 4, 114 - 3, 3, 3, 8 + 4, 4, 4, 12 - 3, 0, 0, 0 + 4, 0, 0, 0 - 95, 17 + 137, 24 2 @@ -267,7 +231,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 3 + 2 True @@ -288,10 +252,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 6 + 4, 7 + + + 4, 0, 4, 0 - 96, 13 + 142, 20 0 @@ -315,10 +282,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s Left, Right - 105, 3 + 154, 4 + + + 4, 4, 4, 4 - 530, 20 + 801, 26 1 @@ -342,13 +312,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 29 + 4, 38 + + + 4, 4, 4, 4 - 3, 0, 0, 0 + 4, 0, 0, 0 - 211, 17 + 313, 24 2 @@ -375,13 +348,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 52 + 4, 70 + + + 4, 4, 4, 4 - 3, 0, 0, 0 + 4, 0, 0, 0 - 181, 17 + 269, 24 3 @@ -405,13 +381,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s Top - 3, 16 + 4, 23 + + + 4, 4, 4, 4 3 - 638, 72 + 959, 98 0 @@ -429,22 +408,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,20" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,30" /></TableLayoutSettings> Fill - 3, 144 + 4, 154 - 3, 3, 3, 10 + 4, 4, 4, 15 - 3, 3, 3, 0 + 4, 4, 4, 0 - 644, 100 + 967, 150 3 @@ -462,7 +441,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 4 + 3 34 @@ -495,13 +474,19 @@ Use this page to review and modify the NRPE configuration and metric threshold s Fill - 3, 257 + 4, 323 + + + 4, 4, 4, 4 62 + + None + - 644, 248 + 967, 411 4 @@ -510,13 +495,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s CheckDataGridView - XenAdmin.Controls.DataGridViewEx.DataGridViewEx, XenCenter, Version=0.0.0.9999, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.DataGridViewEx.DataGridViewEx, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel - 5 + 4 True @@ -531,10 +516,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 24, 0 + 36, 0 + + + 4, 0, 4, 0 - 619, 5 + 928, 32 5 @@ -561,13 +549,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 2, 2 - - - 2, 2, 2, 2 + 3, 3 - 17, 1 + 26, 26 6 @@ -585,16 +570,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s 1 - 2, 510 - - - 2, 2, 2, 2 + 3, 741 1 - 646, 5 + 968, 32 6 @@ -609,7 +591,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s NRPETableLayoutPanel - 6 + 5 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="RetrieveNRPELabel" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="RetrieveNRPEPicture" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="Percent,100" /></TableLayoutSettings> @@ -621,13 +603,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0, 0 - 3, 10, 3, 0 + 4, 15, 4, 0 8 - 650, 537 + 975, 806 0 @@ -645,19 +627,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="BatchConfigurationCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="6" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,20" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="6" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,30" /></TableLayoutSettings> True - 96, 96 + 144, 144 True + + 4, 4, 4, 4 + - 650, 537 + 975, 806 CheckColumn diff --git a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs index ea250c385d..8b3e7cf9ed 100644 --- a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -34,7 +34,7 @@ namespace XenAdmin.Actions.NRPE { - public class NRPEHostConfiguration : ICloneable + public class NRPEHostConfiguration : ICloneable, IEquatable { public const string XAPI_NRPE_PLUGIN_NAME = "nrpe"; public const string XAPI_NRPE_STATUS = "status"; @@ -101,6 +101,29 @@ public bool GetNRPECheck(string name, out Check check) return _checkDict.TryGetValue(name, out check); } + public bool Equals(NRPEHostConfiguration other) + { + if (EnableNRPE != other.EnableNRPE || + !AllowHosts.Equals(other.AllowHosts) || + Debug != other.Debug || + SslLogging != other.SslLogging) + { + return false; + } + foreach (KeyValuePair kvp in CheckDict) + { + Check CurrentCheck = kvp.Value; + other.GetNRPECheck(kvp.Key, out Check OriginalCheck); + if (CurrentCheck != null && OriginalCheck != null + && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) + || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) + { + return false; + } + } + return true; + } + public object Clone() { NRPEHostConfiguration cloned = new NRPEHostConfiguration diff --git a/XenModel/Actions/NRPE/NRPERetrieveAction.cs b/XenModel/Actions/NRPE/NRPERetrieveAction.cs index 9c9b287aa8..495b3bc9ed 100644 --- a/XenModel/Actions/NRPE/NRPERetrieveAction.cs +++ b/XenModel/Actions/NRPE/NRPERetrieveAction.cs @@ -33,6 +33,7 @@ using System.Drawing; using System.Linq; using System.Threading; +using XenAdmin.Core; using XenAPI; @@ -58,46 +59,29 @@ public NRPERetrieveAction(IXenObject host, NRPEHostConfiguration nrpeHostConfigu protected override void Run() { _nrpeCurrentConfig.Status = NRPEHostConfiguration.RetrieveNRPEStatus.Successful; - if (_clone is Pool p) + // For pool, retrieve the configuration from the master of the pool. + IXenObject o = _clone is Pool p ? Helpers.GetCoordinator(p) : _clone; + try { - List hostList = p.Connection.Cache.Hosts.ToList(); - Host checkHost = hostList[0]; - try - { - Host.call_plugin(checkHost.Connection.Session, checkHost.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); - } - catch (Exception e) - { - log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}.", e.Message); - _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") ? - NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; - } + InitNRPEGeneralConfiguration(o); + InitNRPEThreshold(o); } - else + catch (Exception e) { - try - { - InitNRPEGeneralConfiguration(); - InitNRPEThreshold(); - } - catch (Exception e) - { - log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}.", e.Message); - _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") ? - NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; - } + log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}", e.Message); + _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") || e.Message.Contains("The requested plug-in could not be found") ? + NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; } } - private void InitNRPEGeneralConfiguration() + private void InitNRPEGeneralConfiguration(IXenObject o) { - string status = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + string status = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_STATUS, null); log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); _nrpeCurrentConfig.EnableNRPE = status.Trim().Equals("active enabled"); - string nrpeConfig = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + string nrpeConfig = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, null); log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); @@ -122,9 +106,9 @@ private void InitNRPEGeneralConfiguration() } } - private void InitNRPEThreshold() + private void InitNRPEThreshold(IXenObject o) { - string nrpeThreshold = Host.call_plugin(_clone.Connection.Session, _clone.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + string nrpeThreshold = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); diff --git a/XenModel/Actions/NRPE/NRPEUpdateAction.cs b/XenModel/Actions/NRPE/NRPEUpdateAction.cs index f323b02431..cb9060f18d 100644 --- a/XenModel/Actions/NRPE/NRPEUpdateAction.cs +++ b/XenModel/Actions/NRPE/NRPEUpdateAction.cs @@ -56,7 +56,7 @@ protected override void Run() { if (_clone is Host) { - SetNRPEConfigureForHost(); + SetNRPEConfigureForHost(_clone); } else { @@ -64,12 +64,12 @@ protected override void Run() } } - private void SetNRPEConfigureForHost() + private void SetNRPEConfigureForHost(IXenObject o) { // Enable/Disable NRPE if (!_nrpeHostConfiguration.EnableNRPE == _nrpeOriginalConfig.EnableNRPE) { - SetNRPEStatus(_clone, _nrpeHostConfiguration.EnableNRPE); + SetNRPEStatus(o, _nrpeHostConfiguration.EnableNRPE); } if (!_nrpeHostConfiguration.EnableNRPE) // If disable, return { @@ -81,7 +81,7 @@ private void SetNRPEConfigureForHost() || !_nrpeHostConfiguration.Debug.Equals(_nrpeOriginalConfig.Debug) || !_nrpeHostConfiguration.SslLogging.Equals(_nrpeOriginalConfig.SslLogging)) { - SetNRPEGeneralConfiguration(_clone, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, _nrpeHostConfiguration.SslLogging); + SetNRPEGeneralConfiguration(o, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, _nrpeHostConfiguration.SslLogging); } // NRPE Check Threshold @@ -93,45 +93,19 @@ private void SetNRPEConfigureForHost() && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) { - SetNRPEThreshold(_clone, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); + SetNRPEThreshold(o, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); } } - RestartNRPE(_clone); + RestartNRPE(o); } private void SetNRPEConfigureForPool() { - List hostList = null; - if (_clone is Pool p) - { - hostList = p.Connection.Cache.Hosts.ToList(); - } - + List hostList = ((Pool) _clone).Connection.Cache.Hosts.ToList(); hostList.ForEach(host => { - // Enable/Disable NRPE - SetNRPEStatus(host, _nrpeHostConfiguration.EnableNRPE); - if (!_nrpeHostConfiguration.EnableNRPE) // If disable, return - { - return; - } - - // NRPE General Configuration - SetNRPEGeneralConfiguration(host, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, _nrpeHostConfiguration.SslLogging); - - // NRPE Check Threshold - foreach (KeyValuePair kvp in _nrpeHostConfiguration.CheckDict) - { - NRPEHostConfiguration.Check CurrentCheck = kvp.Value; - _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); - if (CurrentCheck != null) - { - SetNRPEThreshold(host, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); - } - } - - RestartNRPE(host); + SetNRPEConfigureForHost(host); }); } From 7dfe809c6696ec7863c7cb384e3030a7164fe6ee Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Wed, 18 Oct 2023 01:01:39 +0800 Subject: [PATCH 09/31] Check NRPE plugin before showing properties dialog. --- XenAdmin/Dialogs/PropertiesDialog.cs | 4 +-- XenAdmin/SettingsPanels/NRPEEditPage.cs | 25 ++++++------------- .../Actions/NRPE/NRPEHostConfiguration.cs | 10 +++----- XenModel/Actions/NRPE/NRPERetrieveAction.cs | 20 ++++++--------- XenModel/Actions/NRPE/NRPEUpdateAction.cs | 18 ++++++------- XenModel/Messages.Designer.cs | 9 ------- XenModel/Messages.resx | 5 +--- XenModel/Utils/Helpers.Versions.cs | 6 +++++ 8 files changed, 37 insertions(+), 60 deletions(-) diff --git a/XenAdmin/Dialogs/PropertiesDialog.cs b/XenAdmin/Dialogs/PropertiesDialog.cs index 1af7923bf1..11a29d89d4 100755 --- a/XenAdmin/Dialogs/PropertiesDialog.cs +++ b/XenAdmin/Dialogs/PropertiesDialog.cs @@ -318,8 +318,8 @@ private void Build() dialog.ShowDialog(Program.MainWindow); } } - if (isPoolOrStandalone && - (connection.Session.IsLocalSuperuser || connection.Session.Roles.Any(r => r.name_label == Role.MR_ROLE_POOL_ADMIN))) + if (isPoolOrStandalone && Helpers.XapiEqualOrGreater_23_27_0(connection) + && (connection.Session.IsLocalSuperuser || connection.Session.Roles.Any(r => r.name_label == Role.MR_ROLE_POOL_ADMIN))) { NRPEEditPage = new NRPEEditPage(); ShowTab(NRPEEditPage); diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index ffbde99d92..9bb719e6c9 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -37,11 +37,15 @@ using XenAdmin.Core; using XenAdmin.Actions.NRPE; using XenAPI; +using System.Linq; +using XenAdmin.Network; namespace XenAdmin.SettingsPanels { public partial class NRPEEditPage : UserControl, IEditPage { + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); @@ -107,13 +111,7 @@ public NRPEEditPage() }; } - public string SubText - { - get - { - return Messages.NRPE_EDIT_PAGE_TEXT; - } - } + public string SubText => Messages.NRPE_EDIT_PAGE_TEXT; public bool ValidToSave { @@ -149,11 +147,7 @@ public bool HasChanged get { UpdateCurrentNRPEConfiguration(); - if (!_nrpeCurrentConfig.Equals(_nrpeOriginalConfig)) - { - return true; - } - return false; + return !_nrpeCurrentConfig.Equals(_nrpeOriginalConfig); } } @@ -236,13 +230,8 @@ private void UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus st RetrieveNRPEPicture.Image = Images.StaticImages._000_error_h32bit_16; RetrieveNRPEPicture.Visible = true; break; - case NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport: - RetrieveNRPELabel.Text = Messages.NRPE_UNSUPPORT; - RetrieveNRPEPicture.Image = Images.StaticImages._000_error_h32bit_16; - RetrieveNRPEPicture.Visible = true; - break; default: - break; + throw new ArgumentOutOfRangeException(nameof(status), status, null); } } diff --git a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs index 8b3e7cf9ed..31154b329f 100644 --- a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -30,7 +30,6 @@ using System; using System.Collections.Generic; -using XenAPI; namespace XenAdmin.Actions.NRPE { @@ -54,7 +53,7 @@ public class NRPEHostConfiguration : ICloneable, IEquatable _checkDict = new Dictionary(); + private readonly Dictionary _checkDict = new Dictionary(); public bool EnableNRPE { get; set; } @@ -72,8 +71,7 @@ public enum RetrieveNRPEStatus { Retrieving, Successful, - Failed, - Unsupport + Failed } public class Check @@ -133,9 +131,9 @@ public object Clone() Debug = Debug, SslLogging = SslLogging }; - foreach (KeyValuePair kvp in _checkDict) + foreach (KeyValuePair kvp in _checkDict) { - NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + Check CurrentCheck = kvp.Value; cloned.AddNRPECheck(new Check(CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold)); } diff --git a/XenModel/Actions/NRPE/NRPERetrieveAction.cs b/XenModel/Actions/NRPE/NRPERetrieveAction.cs index 495b3bc9ed..77513db452 100644 --- a/XenModel/Actions/NRPE/NRPERetrieveAction.cs +++ b/XenModel/Actions/NRPE/NRPERetrieveAction.cs @@ -30,9 +30,6 @@ using System; using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Threading; using XenAdmin.Core; using XenAPI; @@ -69,8 +66,7 @@ protected override void Run() catch (Exception e) { log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}", e.Message); - _nrpeCurrentConfig.Status = e.Message.Contains("UNKNOWN_XENAPI_PLUGIN_FUNCTION") || e.Message.Contains("The requested plug-in could not be found") ? - NRPEHostConfiguration.RetrieveNRPEStatus.Unsupport : NRPEHostConfiguration.RetrieveNRPEStatus.Failed; + _nrpeCurrentConfig.Status = NRPEHostConfiguration.RetrieveNRPEStatus.Failed; } } @@ -128,20 +124,20 @@ private void InitNRPEThreshold(IXenObject o) } } - private string AllowHostsWithoutLocalAddress(string allowHosts) + private static string AllowHostsWithoutLocalAddress(string allowHosts) { - string UpdatedAllowHosts = ""; - string[] AllowHostArray = allowHosts.Split(','); - foreach (string allowHost in AllowHostArray) + string updatedAllowHosts = ""; + string[] allowHostArray = allowHosts.Split(','); + foreach (string allowHost in allowHostArray) { if (!allowHost.Trim().Equals("127.0.0.1") && !allowHost.Trim().Equals("::1")) { - UpdatedAllowHosts += allowHost + ","; + updatedAllowHosts += allowHost + ","; } } - return UpdatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : - UpdatedAllowHosts.Substring(0, UpdatedAllowHosts.Length - 1); + return updatedAllowHosts.Length == 0 ? NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER : + updatedAllowHosts.Substring(0, updatedAllowHosts.Length - 1); } } } diff --git a/XenModel/Actions/NRPE/NRPEUpdateAction.cs b/XenModel/Actions/NRPE/NRPEUpdateAction.cs index cb9060f18d..47bdf9e87b 100644 --- a/XenModel/Actions/NRPE/NRPEUpdateAction.cs +++ b/XenModel/Actions/NRPE/NRPEUpdateAction.cs @@ -87,13 +87,13 @@ private void SetNRPEConfigureForHost(IXenObject o) // NRPE Check Threshold foreach (KeyValuePair kvp in _nrpeHostConfiguration.CheckDict) { - NRPEHostConfiguration.Check CurrentCheck = kvp.Value; + NRPEHostConfiguration.Check currentCheck = kvp.Value; _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); - if (CurrentCheck != null && OriginalCheck != null - && (!CurrentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) - || !CurrentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) + if (currentCheck != null && OriginalCheck != null + && (!currentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) + || !currentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) { - SetNRPEThreshold(o, CurrentCheck.Name, CurrentCheck.WarningThreshold, CurrentCheck.CriticalThreshold); + SetNRPEThreshold(o, currentCheck.Name, currentCheck.WarningThreshold, currentCheck.CriticalThreshold); } } @@ -120,14 +120,14 @@ private void SetNRPEStatus(IXenObject host, bool enableNRPE) private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, bool debug, bool sslLogging) { - Dictionary ConfigArgDict = new Dictionary + Dictionary configArgDict = new Dictionary { { "allowed_hosts", "127.0.0.1,::1," + (allowHosts.Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER) ? "" : allowHosts) }, { "debug", debug ? NRPEHostConfiguration.DEBUG_ENABLE : NRPEHostConfiguration.DEBUG_DISABLE }, { "ssl_logging", sslLogging ? NRPEHostConfiguration.SSL_LOGGING_ENABLE : NRPEHostConfiguration.SSL_LOGGING_DISABLE} }; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, ConfigArgDict); + NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, configArgDict); log.InfoFormat("Execute nrpe {0}, allowed_hosts={1}, debug={2}, ssl_logging={3}, return: {4}", NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, _nrpeHostConfiguration.AllowHosts, @@ -138,14 +138,14 @@ private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, boo private void SetNRPEThreshold(IXenObject host, string checkName, string warningThreshold, string criticalThreshold) { - Dictionary ThresholdArgDict = new Dictionary + Dictionary thresholdArgDict = new Dictionary { { checkName, null }, { "w", warningThreshold }, { "c", criticalThreshold } }; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, - NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, ThresholdArgDict); + NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, thresholdArgDict); log.InfoFormat("Execute nrpe {0}, check={1}, w={2}, c={3}, return: {4}", NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, checkName, diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 92325ebca7..9409d987a7 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29357,15 +29357,6 @@ public static string NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL { } } - /// - /// Looks up a localized string similar to Unsupport NRPE, please upgrade your XenServer version.. - /// - public static string NRPE_UNSUPPORT { - get { - return ResourceManager.GetString("NRPE_UNSUPPORT", resourceCulture); - } - } - /// /// Looks up a localized string similar to Number of snapshots to keep. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 6e390e156c..1df986623f 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10185,9 +10185,6 @@ When you configure an NFS storage repository, you simply provide the host name o Warning threshold should be less than critical threshold. - - Unsupport NRPE, please upgrade your XenServer version. - Number of snapshots to keep @@ -15180,4 +15177,4 @@ Do you want to synchronize immediately? Only synchronize &visible - + \ No newline at end of file diff --git a/XenModel/Utils/Helpers.Versions.cs b/XenModel/Utils/Helpers.Versions.cs index eccfe9652f..a1740bede3 100644 --- a/XenModel/Utils/Helpers.Versions.cs +++ b/XenModel/Utils/Helpers.Versions.cs @@ -528,6 +528,12 @@ public static bool XapiEqualOrGreater_23_18_0(IXenConnection conn) return coordinator == null || ProductVersionCompare(coordinator.GetXapiVersion(), "23.18.0") >= 0; } + public static bool XapiEqualOrGreater_23_27_0(IXenConnection conn) + { + var coordinator = GetCoordinator(conn); + return coordinator == null || ProductVersionCompare(coordinator.GetXapiVersion(), "23.27.0") >= 0; + } + #endregion } } From 2ad5fd8792197066e69503a741eee98c82dfc133 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Mon, 23 Oct 2023 17:05:03 +0800 Subject: [PATCH 10/31] Resolve NRPE code review comments from Tina. --- .../SettingsPanels/NRPEEditPage.CheckGroup.cs | 213 ++++++++++++++ .../SettingsPanels/NRPEEditPage.Designer.cs | 44 +-- XenAdmin/SettingsPanels/NRPEEditPage.cs | 42 ++- XenAdmin/XenAdmin.csproj | 8 +- XenModel/Actions/NRPE/CheckGroup.cs | 267 ------------------ XenModel/Actions/NRPE/NRPERetrieveAction.cs | 23 +- XenModel/Actions/NRPE/NRPEUpdateAction.cs | 29 +- XenModel/Messages.Designer.cs | 4 +- XenModel/Messages.resx | 4 +- XenModel/XenModel.csproj | 2 - 10 files changed, 293 insertions(+), 343 deletions(-) create mode 100644 XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs delete mode 100644 XenModel/Actions/NRPE/CheckGroup.cs diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs new file mode 100644 index 0000000000..268a008ed2 --- /dev/null +++ b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs @@ -0,0 +1,213 @@ +/* Copyright (c) Cloud Software Group, Inc. + * + * Redistribution and use in source and binary forms, + * with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above + * copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +using System.Drawing; +using System.Windows.Forms; + +namespace XenAdmin.SettingsPanels +{ + public partial class NRPEEditPage + { + public class CheckGroup + { + private const decimal THRESHOLD_MINIMUM = 0.01M; + private const decimal THRESHOLD_MAXIMUM = 100M; + + public string Name { get; } + + public DataGridViewRow CheckThresholdRow { get; } + + public DataGridViewTextBoxCell NameCell { get; } + + public DataGridViewTextBoxCell WarningThresholdCell { get; } + + public DataGridViewTextBoxCell CriticalThresholdCell { get; } + + public CheckGroup(string name, string labelName) + { + Name = name; + NameCell = new DataGridViewTextBoxCell { Value = labelName }; + WarningThresholdCell = new DataGridViewTextBoxCell(); + CriticalThresholdCell = new DataGridViewTextBoxCell(); + CheckThresholdRow = new DataGridViewRow(); + CheckThresholdRow.Cells.AddRange(NameCell, WarningThresholdCell, CriticalThresholdCell); + CheckThresholdRow.DefaultCellStyle.Format = "N2"; + CheckThresholdRow.DefaultCellStyle.NullValue = 0; + WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); + } + + public void UpdateThreshold(string warningThreshold, string criticalThreshold) + { + WarningThresholdCell.Value = warningThreshold; + CriticalThresholdCell.Value = criticalThreshold; + WarningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); + } + + public virtual bool CheckValue() + { + WarningThresholdCell.ErrorText = ""; + CriticalThresholdCell.ErrorText = ""; + + return CheckEachValue(WarningThresholdCell) && + CheckEachValue(CriticalThresholdCell) && + CompareWarningAndCritical(); + } + + protected virtual bool CheckEachValue(DataGridViewTextBoxCell cell) + { + string thresholdStr = cell.Value.ToString().Trim(); + if (thresholdStr.Equals("")) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); + return false; + } + + if (!decimal.TryParse(thresholdStr, out decimal threshold)) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_NUMBER); + return false; + } + + if (threshold < THRESHOLD_MINIMUM || threshold > THRESHOLD_MAXIMUM) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_RANGE_ERROR, THRESHOLD_MINIMUM, + THRESHOLD_MAXIMUM); + return false; + } + + cell.ErrorText = ""; + return true; + } + + protected virtual bool CompareWarningAndCritical() + { + decimal.TryParse(WarningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(CriticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal < criticalDecimal) + { + WarningThresholdCell.ErrorText = ""; + return true; + } + else + { + WarningThresholdCell.ErrorText = + string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + } + + public class FreeCheckGroup : CheckGroup + { + public FreeCheckGroup(string name, string labelName) + : base(name, labelName) + { + } + + protected override bool CompareWarningAndCritical() + { + decimal.TryParse(WarningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); + decimal.TryParse(CriticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + WarningThresholdCell.ErrorText = ""; + return true; + } + else + { + WarningThresholdCell.ErrorText = + string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL); + return false; + } + } + + } + + public class HostLoadCheckGroup : CheckGroup + { + public HostLoadCheckGroup(string name, string labelName) + : base(name, labelName) + { + } + } + + public class Dom0LoadCheckGroup : CheckGroup + { + public Dom0LoadCheckGroup(string name, string labelName) + : base(name, labelName) + { + } + + protected override bool CompareWarningAndCritical() + { + string[] warningArray = WarningThresholdCell.Value.ToString().Split(','); + string[] criticalArray = CriticalThresholdCell.Value.ToString().Split(','); + for (int i = 0; i < 3; i++) + { + decimal.TryParse(warningArray[i].Trim(), out decimal warningDecimal); + decimal.TryParse(criticalArray[i].Trim(), out decimal criticalDecimal); + if (warningDecimal > criticalDecimal) + { + WarningThresholdCell.ErrorText = + string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); + return false; + } + } + + WarningThresholdCell.ErrorText = ""; + return true; + } + + protected override bool CheckEachValue(DataGridViewTextBoxCell cell) + { + cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS); + string[] loadArray = cell.Value.ToString().Split(','); + if (loadArray.Length != 3) + { + return false; + } + + foreach (string load in loadArray) + { + bool isDecimal = decimal.TryParse(load, out _); + if (!isDecimal) + { + return false; + } + } + + cell.ErrorText = ""; + return true; + } + } + } +} diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index a619e79ac5..af65fa8f5c 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -40,12 +40,12 @@ private void InitializeComponent() this.DebugLogCheckBox = new System.Windows.Forms.CheckBox(); this.SslDebugLogCheckBox = new System.Windows.Forms.CheckBox(); this.CheckDataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); - this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); - this.RetrieveNRPELabel = new System.Windows.Forms.Label(); - this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); this.CheckColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.WarningThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.CriticalThresholdColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.RetrieveNRPEPanel = new System.Windows.Forms.TableLayoutPanel(); + this.RetrieveNRPELabel = new System.Windows.Forms.Label(); + this.RetrieveNRPEPicture = new System.Windows.Forms.PictureBox(); this.NRPETableLayoutPanel.SuspendLayout(); this.GeneralConfigureGroupBox.SuspendLayout(); this.GeneralConfigTableLayoutPanel.SuspendLayout(); @@ -136,24 +136,8 @@ private void InitializeComponent() this.CheckDataGridView.Name = "CheckDataGridView"; this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.CheckDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; - // - // RetrieveNRPEPanel - // - resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); - this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPELabel, 1, 0); - this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPEPicture, 0, 0); - this.RetrieveNRPEPanel.Name = "RetrieveNRPEPanel"; - // - // RetrieveNRPELabel - // - resources.ApplyResources(this.RetrieveNRPELabel, "RetrieveNRPELabel"); - this.RetrieveNRPELabel.Name = "RetrieveNRPELabel"; - // - // RetrieveNRPEPicture - // - resources.ApplyResources(this.RetrieveNRPEPicture, "RetrieveNRPEPicture"); - this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; - this.RetrieveNRPEPicture.TabStop = false; + this.CheckDataGridView.ShowCellErrors = true; + this.CheckDataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.CheckDataGridView_EndEdit); // // CheckColumn // @@ -174,6 +158,24 @@ private void InitializeComponent() resources.ApplyResources(this.CriticalThresholdColumn, "CriticalThresholdColumn"); this.CriticalThresholdColumn.Name = "CriticalThresholdColumn"; // + // RetrieveNRPEPanel + // + resources.ApplyResources(this.RetrieveNRPEPanel, "RetrieveNRPEPanel"); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPELabel, 1, 0); + this.RetrieveNRPEPanel.Controls.Add(this.RetrieveNRPEPicture, 0, 0); + this.RetrieveNRPEPanel.Name = "RetrieveNRPEPanel"; + // + // RetrieveNRPELabel + // + resources.ApplyResources(this.RetrieveNRPELabel, "RetrieveNRPELabel"); + this.RetrieveNRPELabel.Name = "RetrieveNRPELabel"; + // + // RetrieveNRPEPicture + // + resources.ApplyResources(this.RetrieveNRPEPicture, "RetrieveNRPEPicture"); + this.RetrieveNRPEPicture.Name = "RetrieveNRPEPicture"; + this.RetrieveNRPEPicture.TabStop = false; + // // NRPEEditPage // resources.ApplyResources(this, "$this"); diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index 9bb719e6c9..758526faeb 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -37,15 +37,11 @@ using XenAdmin.Core; using XenAdmin.Actions.NRPE; using XenAPI; -using System.Linq; -using XenAdmin.Network; namespace XenAdmin.SettingsPanels { public partial class NRPEEditPage : UserControl, IEditPage { - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); - private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); @@ -119,8 +115,6 @@ public bool ValidToSave { _invalidParamToolTipText = ""; _invalidParamToolTip.ToolTipTitle = ""; - CheckDataGridView.ShowCellToolTips = false; - CheckDataGridView.ShowCellErrors = false; if (!EnableNRPECheckBox.Checked) { @@ -129,15 +123,23 @@ public bool ValidToSave bool valid = IsAllowHostsValid(); + DataGridViewTextBoxCell focusCellWhenErrorOccurs = null; foreach (CheckGroup checkGroup in _checkGroupList) { if (!checkGroup.CheckValue()) { - CheckDataGridView.ShowCellToolTips = true; - CheckDataGridView.ShowCellErrors = true; valid = false; + if (focusCellWhenErrorOccurs == null) + { + focusCellWhenErrorOccurs = checkGroup.NameCell; + } } } + if (focusCellWhenErrorOccurs != null) + { + CheckDataGridView.CurrentCell = CheckDataGridView.Rows[0].Cells[0]; + CheckDataGridView.CurrentCell = focusCellWhenErrorOccurs; + } return valid; } } @@ -190,7 +192,7 @@ public void SetXenObjects(IXenObject orig, IXenObject clone) UpdateRetrievingNRPETip(NRPEHostConfiguration.RetrieveNRPEStatus.Retrieving); DisableAllComponent(); - NRPERetrieveAction action = new NRPERetrieveAction(_clone, _nrpeOriginalConfig, _checkGroupDictByName, true); + NRPERetrieveAction action = new NRPERetrieveAction(_clone, _nrpeOriginalConfig, true); action.Completed += ActionCompleted; action.RunAsync(); } @@ -250,6 +252,12 @@ private void UpdateComponentValueBasedConfiguration() Color.FromKnownColor(KnownColor.ControlDark) : AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlText); DebugLogCheckBox.Checked = _nrpeOriginalConfig.Debug; SslDebugLogCheckBox.Checked = _nrpeOriginalConfig.SslLogging; + + foreach (KeyValuePair check in _nrpeOriginalConfig.CheckDict) + { + _checkGroupDictByName.TryGetValue(check.Key, out CheckGroup cg); + cg?.UpdateThreshold(check.Value.WarningThreshold, check.Value.CriticalThreshold); + } } private void UpdateComponentStatusBasedEnableNRPECheckBox() @@ -272,13 +280,14 @@ private void UpdateComponentStatusBasedEnableNRPECheckBox() checkGroup.CriticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); } } + CheckDataGridView.ShowCellToolTips = EnableNRPECheckBox.Checked; + CheckDataGridView.ShowCellErrors = EnableNRPECheckBox.Checked; } private bool IsAllowHostsValid() { _invalidParamToolTip.ToolTipTitle = Messages.NRPE_ALLOW_HOSTS_ERROR_TITLE; _invalidParamToolTip.Tag = AllowHostsTextBox; - CheckDataGridView.ShowCellToolTips = true; string str = AllowHostsTextBox.Text; if (str.Trim().Length == 0 || str.Trim().Equals(NRPEHostConfiguration.ALLOW_HOSTS_PLACE_HOLDER)) @@ -316,7 +325,6 @@ private bool IsAllowHostsValid() return false; } } - CheckDataGridView.ShowCellToolTips = false; return true; } @@ -341,14 +349,14 @@ private void UpdateCurrentNRPEConfiguration() _nrpeCurrentConfig = new NRPEHostConfiguration { EnableNRPE = EnableNRPECheckBox.Checked, - AllowHosts = AllowHostsTextBox.Text, + AllowHosts = AllowHostsTextBox.Text.Replace(" ", string.Empty), Debug = DebugLogCheckBox.Checked, SslLogging = SslDebugLogCheckBox.Checked }; foreach (KeyValuePair item in _checkGroupDictByName) { _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(item.Key, - item.Value.WarningThresholdCell.Value.ToString(), item.Value.CriticalThresholdCell.Value.ToString())); + item.Value.WarningThresholdCell.Value.ToString().Trim(), item.Value.CriticalThresholdCell.Value.ToString().Trim())); } } @@ -374,5 +382,13 @@ private void AllowHostsTextBox_LostFocus(object sender, EventArgs e) AllowHostsTextBox.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); } } + + private void CheckDataGridView_EndEdit(object sender, DataGridViewCellEventArgs e) + { + foreach (CheckGroup checkGroup in _checkGroupList) + { + checkGroup.CheckValue(); + } + } } } diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index 0e1b7504d9..5f26b3a417 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -9,7 +9,7 @@ WinExe Properties XenAdmin - XenCenter + [XenCenter] ..\Branding\Images\AppIcon.ico v4.8 publish\ @@ -483,6 +483,10 @@ NRPEEditPage.cs + + NRPEEditPage.cs + UserControl + UserControl @@ -6808,4 +6812,4 @@ copy "$(ProjectDir)\ReportViewer\resource_report.rdlc" "$(TargetDir)" - + \ No newline at end of file diff --git a/XenModel/Actions/NRPE/CheckGroup.cs b/XenModel/Actions/NRPE/CheckGroup.cs deleted file mode 100644 index 3b23469d90..0000000000 --- a/XenModel/Actions/NRPE/CheckGroup.cs +++ /dev/null @@ -1,267 +0,0 @@ -/* Copyright (c) Cloud Software Group, Inc. - * - * Redistribution and use in source and binary forms, - * with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above - * copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -using System.Drawing; -using System.Windows.Forms; - -namespace XenAdmin.Actions.NRPE -{ - public class CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "80"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "90"; - - private readonly decimal THRESHOLD_MINIMUM = 0.01M; - private readonly decimal THRESHOLD_MAXIMUM = 100M; - - private string name; - private string warningThresholdDefault; - private string criticalThresholdDefault; - private bool changed; - - protected DataGridViewRow checkThresholdRow; - protected DataGridViewTextBoxCell nameCell; - protected DataGridViewTextBoxCell warningThresholdCell; - protected DataGridViewTextBoxCell criticalThresholdCell; - - public string Name { get => name; set => name = value; } - public string WarningThresholdDefault { get => warningThresholdDefault; set => warningThresholdDefault = value; } - public string CriticalThresholdDefault { get => criticalThresholdDefault; set => criticalThresholdDefault = value; } - public bool Changed { get => changed; set => changed = value; } - public DataGridViewRow CheckThresholdRow { get => checkThresholdRow; set => checkThresholdRow = value; } - public DataGridViewTextBoxCell NameCell { get => nameCell; set => nameCell = value; } - public DataGridViewTextBoxCell WarningThresholdCell { get => warningThresholdCell; set => warningThresholdCell = value; } - public DataGridViewTextBoxCell CriticalThresholdCell { get => criticalThresholdCell; set => criticalThresholdCell = value; } - - public CheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) - { - InitCheckGroup(name, labelName, warningThresholdDefaultValue, criticalThresholdDefaultValue); - } - - public CheckGroup(string name, string labelName) - { - InitCheckGroup(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD); - } - - private void InitCheckGroup(string name, string labelName, string warningThresholdDefaultValue, string criticalThresholdDefaultValue) - { - Name = name; - nameCell = new DataGridViewTextBoxCell { Value = labelName }; - warningThresholdDefault = warningThresholdDefaultValue; - criticalThresholdDefault = criticalThresholdDefaultValue; - warningThresholdCell = new DataGridViewTextBoxCell { Value = warningThresholdDefaultValue }; - criticalThresholdCell = new DataGridViewTextBoxCell { Value = criticalThresholdDefaultValue }; - checkThresholdRow = new DataGridViewRow(); - checkThresholdRow.Cells.AddRange(nameCell, warningThresholdCell, criticalThresholdCell); - checkThresholdRow.DefaultCellStyle.Format = "N2"; - checkThresholdRow.DefaultCellStyle.NullValue = 0; - warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlDark); - } - - public void UpdateThreshold(string warningThreshold, string criticalThreshold) - { - warningThresholdCell.Value = warningThreshold; - criticalThresholdCell.Value = criticalThreshold; - warningThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - criticalThresholdCell.Style.ForeColor = Color.FromKnownColor(KnownColor.ControlText); - } - - public virtual bool CheckValue() - { - warningThresholdCell.ErrorText = ""; - criticalThresholdCell.ErrorText = ""; - - if (IsEmptyForPool()) - { - return true; - } - - if (CheckEachValue(warningThresholdCell) && - CheckEachValue(criticalThresholdCell) && - CompareWarningAndCritical() && - CheckModifyAllForPool()) - { - return true; - } - return false; - } - - private bool IsEmptyForPool() - { - return warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)); - } - - protected virtual bool CheckEachValue(DataGridViewTextBoxCell cell) - { - string thresholdStr = cell.Value.ToString().Trim(); - if (thresholdStr.Equals("")) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - if (!decimal.TryParse(thresholdStr, out decimal threshold)) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_NUMBER); - return false; - } - if (threshold < THRESHOLD_MINIMUM || threshold > THRESHOLD_MAXIMUM) - { - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_RANGE_ERROR, THRESHOLD_MINIMUM, THRESHOLD_MAXIMUM); - return false; - } - cell.ErrorText = ""; - return true; - } - - protected virtual bool CompareWarningAndCritical() - { - decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); - decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); - if (warningDecimal < criticalDecimal) - { - warningThresholdCell.ErrorText = ""; - return true; - } - else - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); - return false; - } - } - - private bool CheckModifyAllForPool() - { - if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark))) - { - criticalThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - else if (warningThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlDark)) - && criticalThresholdCell.Style.ForeColor.Equals(Color.FromKnownColor(KnownColor.ControlText))) - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_NOT_BE_EMPTY); - return false; - } - return true; - } - } - - public class FreeCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "20"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "10"; - - public FreeCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - - protected override bool CompareWarningAndCritical() - { - decimal.TryParse(warningThresholdCell.Value.ToString().Trim(), out decimal warningDecimal); - decimal.TryParse(criticalThresholdCell.Value.ToString().Trim(), out decimal criticalDecimal); - if (warningDecimal > criticalDecimal) - { - warningThresholdCell.ErrorText = ""; - return true; - } - else - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_BIGGER_THAN_CRITICAL); - return false; - } - } - - } - - public class HostLoadCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "3"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "4"; - - public HostLoadCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - } - - public class Dom0LoadCheckGroup : CheckGroup - { - private static readonly string DEFAULT_CHECK_WARNING_THRESHOLD = "2.7,2.6,2.5"; - private static readonly string DEFAULT_CHECK_CRITICAL_THRESHOLD = "3.2,3.1,3"; - - public Dom0LoadCheckGroup(string name, string labelName) - : base(name, labelName, DEFAULT_CHECK_WARNING_THRESHOLD, DEFAULT_CHECK_CRITICAL_THRESHOLD) - { - } - - protected override bool CompareWarningAndCritical() - { - string[] warningArray = warningThresholdCell.Value.ToString().Split(','); - string[] criticalArray = criticalThresholdCell.Value.ToString().Split(','); - for (int i = 0; i < 3; i++) - { - decimal.TryParse(warningArray[i].Trim(), out decimal warningDecimal); - decimal.TryParse(criticalArray[i].Trim(), out decimal criticalDecimal); - if (warningDecimal > criticalDecimal) - { - warningThresholdCell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_WARNING_SHOULD_LESS_THAN_CRITICAL); - return false; - } - } - warningThresholdCell.ErrorText = ""; - return true; - } - - protected override bool CheckEachValue(DataGridViewTextBoxCell cell) - { - checkThresholdRow.DataGridView.ShowCellToolTips = true; - cell.ErrorText = string.Format(Messages.NRPE_THRESHOLD_SHOULD_BE_3_NUMBERS); - string[] loadArray = cell.Value.ToString().Split(','); - if (loadArray.Length != 3) - { - return false; - } - foreach (string load in loadArray) - { - bool isDecimal = decimal.TryParse(load, out _); - if (!isDecimal) - { - return false; - } - } - cell.ErrorText = ""; - return true; - } - } -} diff --git a/XenModel/Actions/NRPE/NRPERetrieveAction.cs b/XenModel/Actions/NRPE/NRPERetrieveAction.cs index 77513db452..dc5ab62ed4 100644 --- a/XenModel/Actions/NRPE/NRPERetrieveAction.cs +++ b/XenModel/Actions/NRPE/NRPERetrieveAction.cs @@ -29,7 +29,6 @@ */ using System; -using System.Collections.Generic; using XenAdmin.Core; using XenAPI; @@ -41,16 +40,14 @@ public class NRPERetrieveAction : AsyncAction private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly NRPEHostConfiguration _nrpeCurrentConfig; - private readonly Dictionary _checkGroupDictByName; private readonly IXenObject _clone; - public NRPERetrieveAction(IXenObject host, NRPEHostConfiguration nrpeHostConfiguration, Dictionary checkGroupDictByName, bool suppressHistory) + public NRPERetrieveAction(IXenObject host, NRPEHostConfiguration nrpeHostConfiguration, bool suppressHistory) : base(host.Connection, Messages.NRPE_ACTION_RETRIEVING, Messages.NRPE_ACTION_RETRIEVING, suppressHistory) { _clone = host; _nrpeCurrentConfig = nrpeHostConfiguration; - _checkGroupDictByName = checkGroupDictByName; } protected override void Run() @@ -65,7 +62,7 @@ protected override void Run() } catch (Exception e) { - log.ErrorFormat("Execute NRPE plugin failed, failed reason: {0}", e.Message); + log.ErrorFormat("Run NRPE plugin failed, failed reason: {0}", e.Message); _nrpeCurrentConfig.Status = NRPEHostConfiguration.RetrieveNRPEStatus.Failed; } } @@ -74,12 +71,12 @@ private void InitNRPEGeneralConfiguration(IXenObject o) { string status = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_STATUS, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); + log.InfoFormat("Run NRPE {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_STATUS, status); _nrpeCurrentConfig.EnableNRPE = status.Trim().Equals("active enabled"); string nrpeConfig = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); + log.InfoFormat("Run NRPE {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_CONFIG, nrpeConfig); string[] nrpeConfigArray = nrpeConfig.Split('\n'); foreach (string nrpeConfigItem in nrpeConfigArray) @@ -106,21 +103,15 @@ private void InitNRPEThreshold(IXenObject o) { string nrpeThreshold = Host.call_plugin(o.Connection.Session, o.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); + log.InfoFormat("Run NRPE {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_GET_THRESHOLD, nrpeThreshold); string[] nrpeThresholdArray = nrpeThreshold.Split('\n'); foreach (string nrpeThresholdItem in nrpeThresholdArray) { // Return string format for each line: check_cpu warning threshold - 50 critical threshold - 80 string[] thresholdRtnArray = nrpeThresholdItem.Split(' '); - string checkName = thresholdRtnArray[0]; - if (_checkGroupDictByName.TryGetValue(thresholdRtnArray[0], out CheckGroup thresholdCheck)) - { - string warningThreshold = thresholdRtnArray[4]; - string criticalThreshold = thresholdRtnArray[8]; - thresholdCheck.UpdateThreshold(warningThreshold, criticalThreshold); - _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(checkName, warningThreshold, criticalThreshold)); - } + _nrpeCurrentConfig.AddNRPECheck(new NRPEHostConfiguration.Check(thresholdRtnArray[0], + thresholdRtnArray[4], thresholdRtnArray[8])); } } diff --git a/XenModel/Actions/NRPE/NRPEUpdateAction.cs b/XenModel/Actions/NRPE/NRPEUpdateAction.cs index 47bdf9e87b..366d0a5b7f 100644 --- a/XenModel/Actions/NRPE/NRPEUpdateAction.cs +++ b/XenModel/Actions/NRPE/NRPEUpdateAction.cs @@ -30,6 +30,7 @@ using System.Collections.Generic; using System.Linq; +using System.Threading; using XenAPI; @@ -60,7 +61,8 @@ protected override void Run() } else { - SetNRPEConfigureForPool(); + List hostList = ((Pool) _clone).Connection.Cache.Hosts.ToList(); + hostList.ForEach(SetNRPEConfigureForHost); } } @@ -88,10 +90,10 @@ private void SetNRPEConfigureForHost(IXenObject o) foreach (KeyValuePair kvp in _nrpeHostConfiguration.CheckDict) { NRPEHostConfiguration.Check currentCheck = kvp.Value; - _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check OriginalCheck); - if (currentCheck != null && OriginalCheck != null - && (!currentCheck.WarningThreshold.Equals(OriginalCheck.WarningThreshold) - || !currentCheck.CriticalThreshold.Equals(OriginalCheck.CriticalThreshold))) + _nrpeOriginalConfig.GetNRPECheck(kvp.Key, out NRPEHostConfiguration.Check originalCheck); + if (currentCheck != null && originalCheck != null + && (!currentCheck.WarningThreshold.Equals(originalCheck.WarningThreshold) + || !currentCheck.CriticalThreshold.Equals(originalCheck.CriticalThreshold))) { SetNRPEThreshold(o, currentCheck.Name, currentCheck.WarningThreshold, currentCheck.CriticalThreshold); } @@ -100,22 +102,13 @@ private void SetNRPEConfigureForHost(IXenObject o) RestartNRPE(o); } - private void SetNRPEConfigureForPool() - { - List hostList = ((Pool) _clone).Connection.Cache.Hosts.ToList(); - hostList.ForEach(host => - { - SetNRPEConfigureForHost(host); - }); - } - private void SetNRPEStatus(IXenObject host, bool enableNRPE) { string nrpeUpdateStatusMethod = enableNRPE ? NRPEHostConfiguration.XAPI_NRPE_ENABLE : NRPEHostConfiguration.XAPI_NRPE_DISABLE; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, nrpeUpdateStatusMethod, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", nrpeUpdateStatusMethod, result); + log.InfoFormat("Run NRPE {0}, return: {1}", nrpeUpdateStatusMethod, result); } private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, bool debug, bool sslLogging) @@ -128,7 +121,7 @@ private void SetNRPEGeneralConfiguration(IXenObject host, string allowHosts, boo }; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, configArgDict); - log.InfoFormat("Execute nrpe {0}, allowed_hosts={1}, debug={2}, ssl_logging={3}, return: {4}", + log.InfoFormat("Run NRPE {0}, allowed_hosts={1}, debug={2}, ssl_logging={3}, return: {4}", NRPEHostConfiguration.XAPI_NRPE_SET_CONFIG, _nrpeHostConfiguration.AllowHosts, _nrpeHostConfiguration.Debug, @@ -146,7 +139,7 @@ private void SetNRPEThreshold(IXenObject host, string checkName, string warningT }; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, thresholdArgDict); - log.InfoFormat("Execute nrpe {0}, check={1}, w={2}, c={3}, return: {4}", + log.InfoFormat("Run NRPE {0}, check={1}, w={2}, c={3}, return: {4}", NRPEHostConfiguration.XAPI_NRPE_SET_THRESHOLD, checkName, warningThreshold, @@ -159,7 +152,7 @@ private void RestartNRPE(IXenObject host) { string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, NRPEHostConfiguration.XAPI_NRPE_RESTART, null); - log.InfoFormat("Execute nrpe {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_RESTART, result); + log.InfoFormat("Run NRPE {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_RESTART, result); } } } diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index 9409d987a7..d4cbd61736 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29151,7 +29151,7 @@ public static string NRPE_ALLOW_HOSTS_PLACE_HOLDER { } /// - /// Looks up a localized string similar to Please remove duplicated address. + /// Looks up a localized string similar to Please remove duplicate addresses. /// public static string NRPE_ALLOW_HOSTS_SAME_ADDRESS { get { @@ -29286,7 +29286,7 @@ public static string NRPE_INACTIVE { } /// - /// Looks up a localized string similar to Retrieve NRPE configuration failed, please check XenCenter logs.. + /// Looks up a localized string similar to Failed to retrieve NRPE configuration, please check XenCenter logs.. /// public static string NRPE_RETRIEVE_FAILED { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 1df986623f..54838ed18e 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10117,7 +10117,7 @@ When you configure an NFS storage repository, you simply provide the host name o Comma separated IP address or domain list, e.g. 192.168.1.1, test.domain.com - Please remove duplicated address + Please remove duplicate addresses NRPE batch configuration @@ -10162,7 +10162,7 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE service is inactive - Retrieve NRPE configuration failed, please check XenCenter logs. + Failed to retrieve NRPE configuration, please check XenCenter logs. Retrieving NRPE configuration... diff --git a/XenModel/XenModel.csproj b/XenModel/XenModel.csproj index 117ab7806b..1ff3f37a4e 100755 --- a/XenModel/XenModel.csproj +++ b/XenModel/XenModel.csproj @@ -57,7 +57,6 @@ - @@ -89,7 +88,6 @@ - From 28cdeadd948b57e59e3182b8f48a973c8ef23705 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Tue, 24 Oct 2023 09:50:57 +0800 Subject: [PATCH 11/31] Resolve NRPE code review comments from Tina. --- XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs index 268a008ed2..a5893066f2 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs @@ -54,8 +54,8 @@ public CheckGroup(string name, string labelName) { Name = name; NameCell = new DataGridViewTextBoxCell { Value = labelName }; - WarningThresholdCell = new DataGridViewTextBoxCell(); - CriticalThresholdCell = new DataGridViewTextBoxCell(); + WarningThresholdCell = new DataGridViewTextBoxCell { Value = "" }; + CriticalThresholdCell = new DataGridViewTextBoxCell { Value = "" }; CheckThresholdRow = new DataGridViewRow(); CheckThresholdRow.Cells.AddRange(NameCell, WarningThresholdCell, CriticalThresholdCell); CheckThresholdRow.DefaultCellStyle.Format = "N2"; From f7c9d43a64778b44bbb317b61b3ff23b0a42a186 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Tue, 24 Oct 2023 14:02:14 +0100 Subject: [PATCH 12/31] Fixed column resizing on the Graph dialog. Signed-off-by: Konstantina Chremmou --- XenAdmin/Dialogs/GraphDetailsDialog.Designer.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/XenAdmin/Dialogs/GraphDetailsDialog.Designer.cs b/XenAdmin/Dialogs/GraphDetailsDialog.Designer.cs index b48ca2e97c..1d7b7c17ca 100644 --- a/XenAdmin/Dialogs/GraphDetailsDialog.Designer.cs +++ b/XenAdmin/Dialogs/GraphDetailsDialog.Designer.cs @@ -96,9 +96,8 @@ private void InitializeComponent() // this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AllowUserToDeleteRows = false; - this.dataGridView.AllowUserToResizeColumns = false; this.dataGridView.AllowUserToResizeRows = false; - this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; + this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dataGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.dataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; @@ -237,6 +236,7 @@ private void InitializeComponent() // // ColumnDisplayOnGraph // + this.ColumnDisplayOnGraph.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCellsExceptHeader; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle1.NullValue = false; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window; @@ -250,14 +250,12 @@ private void InitializeComponent() // // ColumnName // - this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; this.ColumnName.ReadOnly = true; // // Description // - this.Description.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.Description, "Description"); this.Description.Name = "Description"; this.Description.ReadOnly = true; @@ -271,6 +269,7 @@ private void InitializeComponent() // // ColumnEnabled // + this.ColumnEnabled.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnEnabled, "ColumnEnabled"); this.ColumnEnabled.Name = "ColumnEnabled"; this.ColumnEnabled.ReadOnly = true; From fb9383df119b1912488158b4ff802cdde50669ac Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Tue, 24 Oct 2023 14:50:08 +0100 Subject: [PATCH 13/31] CP-45226: Added friendly name for new datasource 'hostload'. Signed-off-by: Konstantina Chremmou --- XenModel/FriendlyNames.Designer.cs | 9 +++++++++ XenModel/FriendlyNames.resx | 3 +++ XenModel/Utils/Helpers.cs | 7 +++++++ 3 files changed, 19 insertions(+) diff --git a/XenModel/FriendlyNames.Designer.cs b/XenModel/FriendlyNames.Designer.cs index 28e1ec2264..70c62fdabf 100644 --- a/XenModel/FriendlyNames.Designer.cs +++ b/XenModel/FriendlyNames.Designer.cs @@ -5273,6 +5273,15 @@ public static string Message_name_wlb_vm_relocation { } } + /// + /// Looks up a localized string similar to Host CPU Load. + /// + public static string OPERATIONAL_METRICS_HOSTLOAD { + get { + return ResourceManager.GetString("OPERATIONAL_METRICS_HOSTLOAD", resourceCulture); + } + } + /// /// Looks up a localized string similar to There was an error in preparing the host for upgrade.. /// diff --git a/XenModel/FriendlyNames.resx b/XenModel/FriendlyNames.resx index 7b61281332..e2ce0449b1 100644 --- a/XenModel/FriendlyNames.resx +++ b/XenModel/FriendlyNames.resx @@ -1856,6 +1856,9 @@ WLB VM Relocation + + Host CPU Load + There was an error in preparing the host for upgrade. diff --git a/XenModel/Utils/Helpers.cs b/XenModel/Utils/Helpers.cs index 4bf7f0d3d3..f51b067fa3 100755 --- a/XenModel/Utils/Helpers.cs +++ b/XenModel/Utils/Helpers.cs @@ -671,6 +671,7 @@ public static string ToStringI18N(this DataSourceCategory category) static Regex XapiMemoryRegex = new Regex("^xapi_(allocation|free_memory|live_memory|memory_usage)_kib$"); static Regex StatefileLatencyRegex = new Regex("^statefile/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/latency$"); static Regex LoadAvgRegex = new Regex("loadavg"); + static Regex HostLoadRegex = new Regex("hostload"); static Regex SrRegex = new Regex("^sr_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}_cache_(size|hits|misses)"); static Regex SrIORegex = new Regex("^(io_throughput|iops)_(read|write|total)_([a-f0-9]{8})$"); static Regex SrOtherRegex = new Regex("^(latency|avgqu_sz|inflight|iowait)_([a-f0-9]{8})$"); @@ -706,6 +707,9 @@ public static DataSourceCategory GetDataSourceCategory(string name) if (LoadAvgRegex.IsMatch(name)) return DataSourceCategory.LoadAverage; + if (HostLoadRegex.IsMatch(name)) + return DataSourceCategory.LoadAverage; + if (name.StartsWith("pvsaccelerator")) return DataSourceCategory.Pvs; @@ -899,6 +903,9 @@ private static string GetFriendlyDataSourceName_(string name, IXenObject iXenObj if (LoadAvgRegex.IsMatch(name)) return FriendlyNameManager.GetFriendlyName("Label-performance.loadavg"); + if (HostLoadRegex.IsMatch(name)) + return FriendlyNames.OPERATIONAL_METRICS_HOSTLOAD; + return FriendlyNameManager.GetFriendlyName(string.Format("Label-performance.{0}", name)); } From 14a3539f28e85afe644e0d84c18b72ad01c1f12d Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Tue, 24 Oct 2023 11:44:49 +0100 Subject: [PATCH 14/31] CA-384191: Fix missing values for min VM restrictions - Min and max should also include the defaults when looking across all templates - Ensure exception isn't hit unnecessarily when parsing restriction value for VMs - Allow use of `GetRestrictionValueFromMatchingTemplate` with template objects - Parallelize `GetRestrictionValueAcrossTemplates` call Signed-off-by: Danilo Del Busso --- XenModel/XenAPI-Extensions/VM.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/XenModel/XenAPI-Extensions/VM.cs b/XenModel/XenAPI-Extensions/VM.cs index 7915be1e72..d5e578bf4b 100644 --- a/XenModel/XenAPI-Extensions/VM.cs +++ b/XenModel/XenAPI-Extensions/VM.cs @@ -260,7 +260,10 @@ public int MinVCPUs() /// The value if found. If not found, null is returned instead private static T? GetRestrictionValueFromMatchingTemplate(VM vm, string field, string attribute) where T : struct { - if (!vm.is_a_template && !string.IsNullOrEmpty(vm.reference_label)) + if(vm.is_a_template) + return GetRestrictionValue(vm, field, attribute); + + if (!string.IsNullOrEmpty(vm.reference_label)) { var matchingTemplate = vm.Connection.Cache.VMs .FirstOrDefault(v => v.is_a_template && v.reference_label == vm.reference_label); @@ -288,6 +291,13 @@ public int MinVCPUs() var xn = xd?.SelectSingleNode($@"restrictions/restriction[@field='{field}']"); var resultString = xn?.Attributes?[attribute]?.Value; T? result = null; + + // avoid the expensive operation of throwing an exception + if (string.IsNullOrEmpty(resultString)) + { + return null; + } + try { var converter = TypeDescriptor.GetConverter(typeof(T)); @@ -320,6 +330,7 @@ public int MinVCPUs() private static List GetRestrictionValueAcrossTemplates(IXenObject vm, string field, string attribute) where T : struct { return vm.Connection.Cache.VMs + .AsParallel() .Where(v => v.is_a_template) .Select(v => GetRestrictionValue(v, field, attribute)) .Where(value => value != null) @@ -343,7 +354,8 @@ private static T GetMaxRestrictionValue(VM vm, string field, T defaultValue) return (T) value; var templateValues = GetRestrictionValueAcrossTemplates(vm, field, "max"); - return templateValues.Count == 0 ? defaultValue : templateValues.Max(); + templateValues.Add(defaultValue); + return templateValues.Max(); } /// @@ -362,7 +374,8 @@ private static T GetMinRestrictionValue(VM vm, string field, T defaultValue) return (T)value; var templateValues = GetRestrictionValueAcrossTemplates(vm, field, "min"); - return templateValues.Count == 0 ? defaultValue : templateValues.Min(); + templateValues.Add(defaultValue); + return templateValues.Min(); } /// From 3be1d02a11345824887146495342f90103881c7c Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 18 Oct 2023 00:11:55 +0100 Subject: [PATCH 15/31] Minor code smells. Signed-off-by: Konstantina Chremmou --- XenAdmin/Controls/MultipleDvdIsoList.cs | 87 ++++++++++--------- .../Actions/VBD/VbdCreateAndPlugAction.cs | 8 +- 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/XenAdmin/Controls/MultipleDvdIsoList.cs b/XenAdmin/Controls/MultipleDvdIsoList.cs index 5783240024..b923627245 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.cs @@ -44,7 +44,7 @@ namespace XenAdmin.Controls { public partial class MultipleDvdIsoList : UserControl { - bool inRefresh = false; + private bool _inRefresh; public MultipleDvdIsoList() { @@ -61,7 +61,7 @@ public VM VM cdChanger1.VM = value; if (value != null) cdChanger1.VM.PropertyChanged += vm_PropertyChanged; - refreshDrives(); + RefreshDrives(); } get => cdChanger1.VM; } @@ -72,24 +72,24 @@ public VM VM [Category("Appearance")] public Color LabelSingleDvdForeColor { - get { return labelSingleDvd.ForeColor; } - set { labelSingleDvd.ForeColor = value; } + get => labelSingleDvd.ForeColor; + set => labelSingleDvd.ForeColor = value; } [Browsable(true)] [Category("Appearance")] public Color LabelNewCdForeColor { - get { return newCDLabel.ForeColor; } - set { newCDLabel.ForeColor = value; } + get => newCDLabel.ForeColor; + set => newCDLabel.ForeColor = value; } [Browsable(true)] [Category("Appearance")] public Color LinkLabelLinkColor { - get { return linkLabel1.LinkColor; } - set { linkLabel1.LinkColor = value; } + get => linkLabel1.LinkColor; + set => linkLabel1.LinkColor = value; } #endregion @@ -115,24 +115,25 @@ internal virtual void DeregisterEvents() cdChanger1.DeregisterEvents(); } - void vm_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void vm_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "VBDs") - refreshDrives(); + RefreshDrives(); } - private void refreshDrives() + private void RefreshDrives() { VbdCombiItem prevSelection = comboBoxDrive.SelectedItem as VbdCombiItem; - inRefresh = true; + _inRefresh = true; foreach (object o in comboBoxDrive.Items) { - VbdCombiItem v = o as VbdCombiItem; - v.vbd.PropertyChanged -= new PropertyChangedEventHandler(vbd_PropertyChanged); + if (o is VbdCombiItem v) + v.Vbd.PropertyChanged -= vbd_PropertyChanged; } comboBoxDrive.Items.Clear(); + if (VM != null && !VM.is_control_domain) { List vbds = VM.Connection.ResolveAll(VM.VBDs); @@ -142,31 +143,32 @@ private void refreshDrives() VM.Connection.CachePopulated += CachePopulatedMethod; return; } + vbds.RemoveAll(vbd => !vbd.IsCDROM() && !vbd.IsFloppyDrive()); vbds.Sort(); + int dvdCount = 0; int floppyCount = 0; + foreach (VBD vbd in vbds) { - vbd.PropertyChanged +=new PropertyChangedEventHandler(vbd_PropertyChanged); + vbd.PropertyChanged += vbd_PropertyChanged; + VbdCombiItem item; + if (vbd.IsCDROM()) { dvdCount++; - VbdCombiItem i = new VbdCombiItem(); - i.name = string.Format(Messages.DVD_DRIVE_LABEL_NUMBERED, dvdCount); - i.vbd = vbd; - comboBoxDrive.Items.Add(i); + item = new VbdCombiItem(string.Format(Messages.DVD_DRIVE_LABEL_NUMBERED, dvdCount), vbd); } else { floppyCount++; - VbdCombiItem i = new VbdCombiItem(); - i.name = string.Format(Messages.FLOPPY_DRIVE_LABEL_NUMBERED, floppyCount); - i.vbd = vbd; - comboBoxDrive.Items.Add(i); - } + item = new VbdCombiItem(string.Format(Messages.FLOPPY_DRIVE_LABEL_NUMBERED, floppyCount), vbd); + } + comboBoxDrive.Items.Add(item); } } + if (comboBoxDrive.Items.Count == 0) { comboBoxDrive.Visible = false; @@ -197,54 +199,59 @@ private void refreshDrives() newCDLabel.Visible = false; linkLabel1.Visible = true; } - inRefresh = false; + + _inRefresh = false; + // Restore prev selection or select the top item by default if (prevSelection != null) { foreach (object o in comboBoxDrive.Items) { - VbdCombiItem v = o as VbdCombiItem; - if (v.vbd.uuid == prevSelection.vbd.uuid) + if (o is VbdCombiItem v && v.Vbd.uuid == prevSelection.Vbd.uuid) { comboBoxDrive.SelectedItem = o; return; } } } - if (comboBoxDrive.Items.Count == 0) - comboBoxDrive.SelectedItem = null; - else - comboBoxDrive.SelectedItem = comboBoxDrive.Items[0]; + + comboBoxDrive.SelectedItem = comboBoxDrive.Items.Count == 0 ? null : comboBoxDrive.Items[0]; } - void vbd_PropertyChanged(object sender, PropertyChangedEventArgs e) + private void vbd_PropertyChanged(object sender, PropertyChangedEventArgs e) { - refreshDrives(); + RefreshDrives(); } private void CachePopulatedMethod(IXenConnection conn) { VM.Connection.CachePopulated -= CachePopulatedMethod; - refreshDrives(); + RefreshDrives(); } - internal class VbdCombiItem + private class VbdCombiItem { - public string name; - public VBD vbd; + public string Name { get; } + public VBD Vbd { get; } + + public VbdCombiItem(string name, VBD vbd) + { + Name = name; + Vbd = vbd; + } public override string ToString() { - return name; + return Name; } } private void comboBoxDrive_SelectedIndexChanged(object sender, EventArgs e) { - if (inRefresh) + if (_inRefresh) return; - cdChanger1.Drive = (comboBoxDrive.SelectedItem as VbdCombiItem)?.vbd; + cdChanger1.Drive = (comboBoxDrive.SelectedItem as VbdCombiItem)?.Vbd; } diff --git a/XenModel/Actions/VBD/VbdCreateAndPlugAction.cs b/XenModel/Actions/VBD/VbdCreateAndPlugAction.cs index a54320365c..7d33de9542 100644 --- a/XenModel/Actions/VBD/VbdCreateAndPlugAction.cs +++ b/XenModel/Actions/VBD/VbdCreateAndPlugAction.cs @@ -62,7 +62,7 @@ public VbdCreateAndPlugAction(VM vm, VBD vbd, string vdiName, bool suppress) protected override void Run() { - string vbdServerRef = VBD.create(Session, vbd); + string vbdRef = VBD.create(Session, vbd); if (!VM.IsHVM() && vbd.empty) { @@ -71,12 +71,12 @@ protected override void Run() } // Then if we can plug the vbd in, do so... - if (vbdServerRef != null && - VBD.get_allowed_operations(Session, vbdServerRef).Contains(vbd_operations.plug)) + if (vbdRef != null && + VBD.get_allowed_operations(Session, vbdRef).Contains(vbd_operations.plug)) { log.DebugFormat("Attempting to hot plug VBD {0}.", vbd.uuid); - RelatedTask = VBD.async_plug(Session, vbdServerRef); + RelatedTask = VBD.async_plug(Session, vbdRef); PollToCompletion(); Description = Messages.ATTACHDISKWIZARD_ATTACHED; } From fcd9b195f6d00146d7e21d3d221791f3442bfcf1 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 18 Oct 2023 00:51:02 +0100 Subject: [PATCH 16/31] Minor layout tweaks (margins, padding, alignment). Signed-off-by: Konstantina Chremmou --- .../Controls/ComboBoxes/ISODropDownBox.cs | 2 + .../Controls/MultipleDvdIsoList.Designer.cs | 33 +-- XenAdmin/Controls/MultipleDvdIsoList.cs | 15 +- XenAdmin/Controls/MultipleDvdIsoList.resx | 218 +++++++----------- 4 files changed, 98 insertions(+), 170 deletions(-) diff --git a/XenAdmin/Controls/ComboBoxes/ISODropDownBox.cs b/XenAdmin/Controls/ComboBoxes/ISODropDownBox.cs index d7d1f202b5..45e85dc16e 100644 --- a/XenAdmin/Controls/ComboBoxes/ISODropDownBox.cs +++ b/XenAdmin/Controls/ComboBoxes/ISODropDownBox.cs @@ -232,6 +232,8 @@ private void AddSR(ToStringWrapper srWrapper) } } + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IXenConnection connection { set diff --git a/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs b/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs index 8c0f39680c..048d614f53 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs @@ -36,11 +36,9 @@ private void InitializeComponent() this.newCDLabel = new System.Windows.Forms.Label(); this.comboBoxDrive = new System.Windows.Forms.ComboBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); - this.panel1 = new System.Windows.Forms.Panel(); this.cdChanger1 = new XenAdmin.Controls.CDChanger(); - this.linkLabel1 = new System.Windows.Forms.LinkLabel(); + this.linkLabelEject = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel1.SuspendLayout(); - this.panel1.SuspendLayout(); this.SuspendLayout(); // // labelSingleDvd @@ -51,6 +49,7 @@ private void InitializeComponent() // newCDLabel // resources.ApplyResources(this.newCDLabel, "newCDLabel"); + this.tableLayoutPanel1.SetColumnSpan(this.newCDLabel, 4); this.newCDLabel.Cursor = System.Windows.Forms.Cursors.Hand; this.newCDLabel.ForeColor = System.Drawing.SystemColors.HotTrack; this.newCDLabel.Name = "newCDLabel"; @@ -69,20 +68,13 @@ private void InitializeComponent() resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelSingleDvd, 0, 0); this.tableLayoutPanel1.Controls.Add(this.comboBoxDrive, 1, 0); - this.tableLayoutPanel1.Controls.Add(this.newCDLabel, 2, 1); - this.tableLayoutPanel1.Controls.Add(this.panel1, 2, 0); + this.tableLayoutPanel1.Controls.Add(this.cdChanger1, 2, 0); + this.tableLayoutPanel1.Controls.Add(this.linkLabelEject, 3, 0); + this.tableLayoutPanel1.Controls.Add(this.newCDLabel, 0, 1); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // - // panel1 - // - resources.ApplyResources(this.panel1, "panel1"); - this.panel1.Controls.Add(this.cdChanger1); - this.panel1.Controls.Add(this.linkLabel1); - this.panel1.Name = "panel1"; - // // cdChanger1 // - this.cdChanger1.connection = null; resources.ApplyResources(this.cdChanger1, "cdChanger1"); this.cdChanger1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.cdChanger1.DropDownHeight = 500; @@ -90,12 +82,12 @@ private void InitializeComponent() this.cdChanger1.FormattingEnabled = true; this.cdChanger1.Name = "cdChanger1"; // - // linkLabel1 + // linkLabelEject // - resources.ApplyResources(this.linkLabel1, "linkLabel1"); - this.linkLabel1.Name = "linkLabel1"; - this.linkLabel1.TabStop = true; - this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); + resources.ApplyResources(this.linkLabelEject, "linkLabelEject"); + this.linkLabelEject.Name = "linkLabelEject"; + this.linkLabelEject.TabStop = true; + this.linkLabelEject.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelEject_LinkClicked); // // MultipleDvdIsoList // @@ -105,8 +97,6 @@ private void InitializeComponent() this.Name = "MultipleDvdIsoList"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); - this.panel1.ResumeLayout(false); - this.panel1.PerformLayout(); this.ResumeLayout(false); } @@ -118,7 +108,6 @@ private void InitializeComponent() private System.Windows.Forms.ComboBox comboBoxDrive; private System.Windows.Forms.Label newCDLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private System.Windows.Forms.Panel panel1; - private System.Windows.Forms.LinkLabel linkLabel1; + private System.Windows.Forms.LinkLabel linkLabelEject; } } diff --git a/XenAdmin/Controls/MultipleDvdIsoList.cs b/XenAdmin/Controls/MultipleDvdIsoList.cs index b923627245..9a8f22bfc3 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.cs @@ -88,8 +88,8 @@ public Color LabelNewCdForeColor [Category("Appearance")] public Color LinkLabelLinkColor { - get => linkLabel1.LinkColor; - set => linkLabel1.LinkColor = value; + get => linkLabelEject.LinkColor; + set => linkLabelEject.LinkColor = value; } #endregion @@ -174,8 +174,7 @@ private void RefreshDrives() comboBoxDrive.Visible = false; cdChanger1.Visible = false; labelSingleDvd.Visible = false; - linkLabel1.Visible = false; - panel1.Visible = false; + linkLabelEject.Visible = false; newCDLabel.Visible = VM != null && !VM.is_control_domain; } @@ -187,17 +186,15 @@ private void RefreshDrives() labelSingleDvd.Visible = true; tableLayoutPanel1.ColumnStyles[0].Width = labelSingleDvd.Width; newCDLabel.Visible = false; - panel1.Visible = true; - linkLabel1.Visible = true; + linkLabelEject.Visible = true; } else { comboBoxDrive.Visible = true; cdChanger1.Visible = true; labelSingleDvd.Visible = false; - panel1.Visible = true; newCDLabel.Visible = false; - linkLabel1.Visible = true; + linkLabelEject.Visible = true; } _inRefresh = false; @@ -279,7 +276,7 @@ private void CreateDriveAction_ShowUserInstruction(string message) }); } - private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + private void linkLabelEject_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (cdChanger1.Drive != null) cdChanger1.ChangeCD(null); diff --git a/XenAdmin/Controls/MultipleDvdIsoList.resx b/XenAdmin/Controls/MultipleDvdIsoList.resx index c0590c8d7f..38965f8799 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.resx +++ b/XenAdmin/Controls/MultipleDvdIsoList.resx @@ -117,39 +117,30 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Left + True - - - Fill - NoControl - 3, 8 - - - 3, 8, 3, 5 - - - 100, 23 + 3, 7 - 61, 15 + 61, 13 - 1 + 0 DVD Dr&ive: - - TopRight - labelSingleDvd @@ -162,65 +153,23 @@ 0 + + Left, Right + True - - Fill - - - Microsoft Sans Serif, 8.25pt, style=Bold, Underline - - - NoControl - - - 173, 30 - - - 0, 2, 2, 0 - - - 942, 47 - - - 3 - - - Click here to create a DVD drive - - - MiddleLeft - - - False - - - newCDLabel - - - System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - tableLayoutPanel1 - - - 2 + + 4 - 70, 4 - - - 3, 4, 3, 3 - - - 120, 0 + 70, 3 100, 21 - 2 + 1 False @@ -237,17 +186,8 @@ 1 - - 4 - - - True - - - GrowAndShrink - - - Fill + + Left, Right False @@ -256,93 +196,57 @@ 15 - 0, 5 + 176, 3 - 907, 21 + 456, 21 - 0 + 2 cdChanger1 - XenAdmin.Controls.CDChanger, XenCenterMain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.CDChanger, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - panel1 + tableLayoutPanel1 - 0 + 2 - - True + + Left - - Right + + True - + NoControl - - 907, 5 + + 638, 7 - - 3, 3, 3, 3 + + 31, 13 - - 3, 5, 3, 3 - - - 37, 21 - - - 1 + + 3 - + Eject - - linkLabel1 + + linkLabelEject - + System.Windows.Forms.LinkLabel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - panel1 - - - 1 - - - Fill - - - 173, 0 - - - 0, 0, 0, 0 - - - 0, 5, 0, 5 - - - 944, 28 - - - 40 - - - panel1 - - - System.Windows.Forms.Panel, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - + tableLayoutPanel1 - + 3 @@ -355,10 +259,10 @@ 2 - 1117, 77 + 672, 77 - 40 + 0 tableLayoutPanel1 @@ -373,7 +277,43 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelSingleDvd" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="comboBoxDrive" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="newCDLabel" Row="1" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="panel1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0" /><Rows Styles="AutoSize,0,Percent,100" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelSingleDvd" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="comboBoxDrive" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="cdChanger1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="linkLabelEject" Row="0" RowSpan="1" Column="3" ColumnSpan="1" /><Control Name="newCDLabel" Row="1" RowSpan="1" Column="0" ColumnSpan="4" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0" /><Rows Styles="AutoSize,0,Percent,100" /></TableLayoutSettings> + + + Microsoft Sans Serif, 8.25pt, style=Bold, Underline + + + NoControl + + + 3, 45 + + + 666, 13 + + + 4 + + + Click here to create a DVD drive + + + TopCenter + + + False + + + newCDLabel + + + System.Windows.Forms.Label, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + tableLayoutPanel1 + + + 4 True @@ -382,7 +322,7 @@ 96, 96 - 1117, 77 + 672, 77 MultipleDvdIsoList From 736f338cd210f46e19fbdd60ded6c0a60dc18858 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Mon, 30 Oct 2023 11:18:08 +0000 Subject: [PATCH 17/31] Added tooltips with the original check names. Signed-off-by: Konstantina Chremmou --- XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs | 2 +- XenModel/Messages.Designer.cs | 9 +++++++++ XenModel/Messages.resx | 3 +++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs index a5893066f2..8f9f3f24d1 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.CheckGroup.cs @@ -53,7 +53,7 @@ public class CheckGroup public CheckGroup(string name, string labelName) { Name = name; - NameCell = new DataGridViewTextBoxCell { Value = labelName }; + NameCell = new DataGridViewTextBoxCell { Value = labelName, ToolTipText = string.Format(Messages.NRPE_METRIC_TOOLTIP, name) }; WarningThresholdCell = new DataGridViewTextBoxCell { Value = "" }; CriticalThresholdCell = new DataGridViewTextBoxCell { Value = "" }; CheckThresholdRow = new DataGridViewRow(); diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index d4cbd61736..ec1a7419f9 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29285,6 +29285,15 @@ public static string NRPE_INACTIVE { } } + /// + /// Looks up a localized string similar to NRPE check name: {0}. + /// + public static string NRPE_METRIC_TOOLTIP { + get { + return ResourceManager.GetString("NRPE_METRIC_TOOLTIP", resourceCulture); + } + } + /// /// Looks up a localized string similar to Failed to retrieve NRPE configuration, please check XenCenter logs.. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 54838ed18e..be0c523ec2 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10161,6 +10161,9 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE service is inactive + + NRPE check name: {0} + Failed to retrieve NRPE configuration, please check XenCenter logs. From 2e9c144bd9f343e5725325720ac81bdf13b19a43 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Tue, 31 Oct 2023 11:03:50 +0000 Subject: [PATCH 18/31] Corrected sizes. Signed-off-by: Konstantina Chremmou --- .../SettingsPanels/NRPEEditPage.Designer.cs | 2 +- XenAdmin/SettingsPanels/NRPEEditPage.resx | 119 ++++++++---------- 2 files changed, 50 insertions(+), 71 deletions(-) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs index af65fa8f5c..2fee41b34f 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.Designer.cs @@ -126,12 +126,12 @@ private void InitializeComponent() // this.CheckDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.CheckDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; - resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); this.CheckDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.CheckDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.CheckColumn, this.WarningThresholdColumn, this.CriticalThresholdColumn}); + resources.ApplyResources(this.CheckDataGridView, "CheckDataGridView"); this.CheckDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; this.CheckDataGridView.Name = "CheckDataGridView"; this.CheckDataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.resx b/XenAdmin/SettingsPanels/NRPEEditPage.resx index 3250d8794e..a8f49ac6f7 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.resx +++ b/XenAdmin/SettingsPanels/NRPEEditPage.resx @@ -133,13 +133,13 @@ - 4, 0 + 3, 0 - 4, 0, 4, 15 + 3, 0, 3, 10 - 967, 40 + 644, 26 0 @@ -152,7 +152,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s DescLabelPool - XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -170,13 +170,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 55 + 3, 36 - 4, 0, 4, 15 + 3, 0, 3, 10 - 967, 40 + 644, 26 1 @@ -189,7 +189,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s DescLabelHost - XenAdmin.Controls.Common.AutoHeightLabel, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.Common.AutoHeightLabel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -204,16 +204,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 114 + 3, 75 - 4, 4, 4, 12 + 3, 3, 3, 8 - 4, 0, 0, 0 + 3, 0, 0, 0 - 137, 24 + 95, 17 2 @@ -252,13 +252,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 7 - - - 4, 0, 4, 0 + 3, 6 - 142, 20 + 96, 13 0 @@ -282,13 +279,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s Left, Right - 154, 4 - - - 4, 4, 4, 4 + 105, 3 - 801, 26 + 530, 20 1 @@ -312,16 +306,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 38 - - - 4, 4, 4, 4 + 3, 29 - 4, 0, 0, 0 + 3, 0, 0, 0 - 313, 24 + 211, 17 2 @@ -348,16 +339,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 4, 70 - - - 4, 4, 4, 4 + 3, 52 - 4, 0, 0, 0 + 3, 0, 0, 0 - 269, 24 + 181, 17 3 @@ -381,16 +369,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s Top - 4, 23 - - - 4, 4, 4, 4 + 3, 16 3 - 959, 98 + 638, 72 0 @@ -408,22 +393,22 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,30" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="AllowHostsLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="AllowHostsTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="DebugLogCheckBox" Row="1" RowSpan="1" Column="0" ColumnSpan="2" /><Control Name="SslDebugLogCheckBox" Row="2" RowSpan="1" Column="0" ColumnSpan="2" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,20" /></TableLayoutSettings> Fill - 4, 154 + 3, 103 - 4, 4, 4, 15 + 3, 3, 3, 10 - 4, 4, 4, 0 + 3, 3, 3, 0 - 967, 150 + 644, 100 3 @@ -443,9 +428,6 @@ Use this page to review and modify the NRPE configuration and metric threshold s 3 - - 34 - Metric @@ -474,10 +456,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s Fill - 4, 323 - - - 4, 4, 4, 4 + 3, 216 62 @@ -486,7 +465,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s None - 967, 411 + 644, 273 4 @@ -495,7 +474,7 @@ Use this page to review and modify the NRPE configuration and metric threshold s CheckDataGridView - XenAdmin.Controls.DataGridViewEx.DataGridViewEx, XenCenter, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.DataGridViewEx.DataGridViewEx, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null NRPETableLayoutPanel @@ -516,13 +495,10 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 36, 0 - - - 4, 0, 4, 0 + 24, 0 - 928, 32 + 619, 21 5 @@ -549,10 +525,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s NoControl - 3, 3 + 2, 2 + + + 2, 2, 2, 2 - 26, 26 + 17, 17 6 @@ -570,13 +549,16 @@ Use this page to review and modify the NRPE configuration and metric threshold s 1 - 3, 741 + 2, 494 + + + 2, 2, 2, 2 1 - 968, 32 + 646, 21 6 @@ -603,13 +585,13 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0, 0 - 4, 15, 4, 0 + 3, 10, 3, 0 8 - 975, 806 + 650, 537 0 @@ -627,22 +609,19 @@ Use this page to review and modify the NRPE configuration and metric threshold s 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="6" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,30" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="DescLabelPool" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="DescLabelHost" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="EnableNRPECheckBox" Row="3" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="GeneralConfigureGroupBox" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="CheckDataGridView" Row="5" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="RetrieveNRPEPanel" Row="6" RowSpan="1" Column="0" ColumnSpan="1" /></Controls><Columns Styles="Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,Absolute,20" /></TableLayoutSettings> True - 144, 144 + 96, 96 True - - 4, 4, 4, 4 - - 975, 806 + 650, 537 CheckColumn From 85347aa95c9ad3e17264e86aec15fbb2fa933f6e Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 1 Nov 2023 00:27:46 +0000 Subject: [PATCH 19/31] CP-43651: Ask for confirmation when the user clicks to create a DVD drive. Signed-off-by: Konstantina Chremmou --- XenAdmin/Controls/MultipleDvdIsoList.cs | 23 ++++++++++++++++------- XenModel/Messages.Designer.cs | 20 ++++++++++++++++++++ XenModel/Messages.resx | 8 ++++++++ 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/XenAdmin/Controls/MultipleDvdIsoList.cs b/XenAdmin/Controls/MultipleDvdIsoList.cs index 9a8f22bfc3..621023d36d 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.cs @@ -251,17 +251,26 @@ private void comboBoxDrive_SelectedIndexChanged(object sender, EventArgs e) cdChanger1.Drive = (comboBoxDrive.SelectedItem as VbdCombiItem)?.Vbd; } - private void newCDLabel_Click(object sender, EventArgs e) { - if (VM != null) - { - var createDriveAction = new CreateCdDriveAction(VM); - createDriveAction.ShowUserInstruction += CreateDriveAction_ShowUserInstruction; + if (VM == null) + return; - using (var dlg = new ActionProgressDialog(createDriveAction, ProgressBarStyle.Marquee)) - dlg.ShowDialog(this); + if (VM.IsHVM()) + { + using (var dialog = new WarningDialog( + string.Format(Messages.NEW_DVD_DRIVE_CREATE_CONFIRMATION, VM.Name()), + new ThreeButtonDialog.TBDButton(Messages.NEW_DVD_DRIVE_CREATE_YES_BUTTON, DialogResult.Yes, ThreeButtonDialog.ButtonType.ACCEPT, true), + ThreeButtonDialog.ButtonNo)) + if (dialog.ShowDialog(Program.MainWindow) != DialogResult.Yes) + return; } + + var createDriveAction = new CreateCdDriveAction(VM); + createDriveAction.ShowUserInstruction += CreateDriveAction_ShowUserInstruction; + + using (var dlg = new ActionProgressDialog(createDriveAction, ProgressBarStyle.Marquee)) + dlg.ShowDialog(this); } private void CreateDriveAction_ShowUserInstruction(string message) diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index bf9759448b..54493ad622 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -26209,6 +26209,17 @@ public static string NEVER { } } + /// + /// Looks up a localized string similar to Are you sure you want to create a new DVD drive on VM '{0}'? + /// + ///This action will create a new Virtual Block Device (VBD) that cannot be hot-unplugged.. + /// + public static string NEW_DVD_DRIVE_CREATE_CONFIRMATION { + get { + return ResourceManager.GetString("NEW_DVD_DRIVE_CREATE_CONFIRMATION", resourceCulture); + } + } + /// /// Looks up a localized string similar to Creating new DVD drive on VM {0}. /// @@ -26218,6 +26229,15 @@ public static string NEW_DVD_DRIVE_CREATE_TITLE { } } + /// + /// Looks up a localized string similar to &Yes, Create. + /// + public static string NEW_DVD_DRIVE_CREATE_YES_BUTTON { + get { + return ResourceManager.GetString("NEW_DVD_DRIVE_CREATE_YES_BUTTON", resourceCulture); + } + } + /// /// Looks up a localized string similar to Creating new DVD drive. /// diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index c0ca9f5923..3e9565a6cd 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -9101,9 +9101,17 @@ You should only proceed if you have verified that these settings are correct. Never + + Are you sure you want to create a new DVD drive on VM '{0}'? + +This action will create a new Virtual Block Device (VBD) that cannot be hot-unplugged. + Creating new DVD drive on VM {0} + + &Yes, Create + Creating new DVD drive From 6f1daff1fc7a5027df45cf91584cf2b20b3fba0d Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 1 Nov 2023 00:47:51 +0000 Subject: [PATCH 20/31] Compacted logic that toggles control visibility. Signed-off-by: Konstantina Chremmou --- XenAdmin/Controls/MultipleDvdIsoList.cs | 33 ++++++------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/XenAdmin/Controls/MultipleDvdIsoList.cs b/XenAdmin/Controls/MultipleDvdIsoList.cs index 621023d36d..0376a4ae37 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.cs @@ -169,33 +169,14 @@ private void RefreshDrives() } } - if (comboBoxDrive.Items.Count == 0) - { - comboBoxDrive.Visible = false; - cdChanger1.Visible = false; - labelSingleDvd.Visible = false; - linkLabelEject.Visible = false; - newCDLabel.Visible = VM != null && !VM.is_control_domain; - - } - else if (comboBoxDrive.Items.Count == 1) - { - comboBoxDrive.Visible = false; - cdChanger1.Visible = true; + labelSingleDvd.Visible = comboBoxDrive.Items.Count == 1; + if (labelSingleDvd.Visible) labelSingleDvd.Text = comboBoxDrive.Items[0].ToString(); - labelSingleDvd.Visible = true; - tableLayoutPanel1.ColumnStyles[0].Width = labelSingleDvd.Width; - newCDLabel.Visible = false; - linkLabelEject.Visible = true; - } - else - { - comboBoxDrive.Visible = true; - cdChanger1.Visible = true; - labelSingleDvd.Visible = false; - newCDLabel.Visible = false; - linkLabelEject.Visible = true; - } + + comboBoxDrive.Visible = comboBoxDrive.Items.Count > 1; + cdChanger1.Visible = comboBoxDrive.Items.Count > 0; + linkLabelEject.Visible = comboBoxDrive.Items.Count > 0; + newCDLabel.Visible = comboBoxDrive.Items.Count == 0 && VM != null && !VM.is_control_domain; _inRefresh = false; From e28aa63aa5b42678045a7e6541a4075738130888 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 1 Nov 2023 01:17:52 +0000 Subject: [PATCH 21/31] The user could not create DVD from the Console TabPage while the same operation was possible from the VmStorage TabPage. Signed-off-by: Konstantina Chremmou --- XenAdmin/ConsoleView/VNCTabView.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/XenAdmin/ConsoleView/VNCTabView.cs b/XenAdmin/ConsoleView/VNCTabView.cs index bb3314f8c6..7a3e97b611 100644 --- a/XenAdmin/ConsoleView/VNCTabView.cs +++ b/XenAdmin/ConsoleView/VNCTabView.cs @@ -1291,10 +1291,12 @@ internal void VMPowerOff() { toggleConsoleButton.Enabled = false; - VBD cddrive = source.FindVMCDROM(); - bool allowEject = cddrive != null ? cddrive.allowed_operations.Contains(vbd_operations.eject) : false; - bool allowInsert = cddrive != null ? cddrive.allowed_operations.Contains(vbd_operations.insert) : false; - multipleDvdIsoList1.Enabled = (source.power_state == vm_power_state.Halted) && (allowEject || allowInsert); + VBD cdDrive = source.FindVMCDROM(); + + multipleDvdIsoList1.Enabled = cdDrive == null || + source.power_state == vm_power_state.Halted && + (cdDrive.allowed_operations.Contains(vbd_operations.eject) || + cdDrive.allowed_operations.Contains(vbd_operations.insert)); sendCAD.Enabled = false; } From 7a3d17fdb9ea4710ccf59af6cf75ced39e46b8e1 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Mon, 30 Oct 2023 23:17:08 +0800 Subject: [PATCH 22/31] CA-384333: Update IPv4 regex and remove redundant codes. --- XenAdmin/SettingsPanels/NRPEEditPage.cs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/XenAdmin/SettingsPanels/NRPEEditPage.cs b/XenAdmin/SettingsPanels/NRPEEditPage.cs index 758526faeb..6dd28e0ca0 100644 --- a/XenAdmin/SettingsPanels/NRPEEditPage.cs +++ b/XenAdmin/SettingsPanels/NRPEEditPage.cs @@ -42,7 +42,7 @@ namespace XenAdmin.SettingsPanels { public partial class NRPEEditPage : UserControl, IEditPage { - private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"); + private static readonly Regex REGEX_IPV4 = new Regex("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"); private static readonly Regex REGEX_IPV4_CIDR = new Regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}(\\/([0-9]|[1-2][0-9]|3[0-2]))?$"); private static readonly Regex REGEX_DOMAIN = new Regex("^(((?!-))(xn--|_)?[a-z0-9-]{0,61}[a-z0-9]{1,1}\\.)*(xn--)?([a-z0-9][a-z0-9\\-]{0,60}|[a-z0-9-]{1,30}\\.[a-z]{2,})$"); @@ -315,16 +315,6 @@ private bool IsAllowHostsValid() } } } - foreach (string host in hostArray) - { - if (!REGEX_IPV4.Match(host.Trim()).Success && - !REGEX_IPV4_CIDR.Match(host.Trim()).Success && - !REGEX_DOMAIN.Match(host.Trim()).Success) - { - _invalidParamToolTipText = Messages.NRPE_ALLOW_HOSTS_FORMAT_ERROR; - return false; - } - } return true; } From e42f6078999868fe71a42e600a553460ddd5154e Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Mon, 30 Oct 2023 15:16:30 +0000 Subject: [PATCH 23/31] CP-40844: Bumped pipeline version to v4.11. Signed-off-by: Konstantina Chremmou --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 32677764e7..452c8e03a8 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -32,7 +32,7 @@ def XENADMIN_BRANDING_TAG = 'v5.3' -@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.10"]) +@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.11"]) import com.xenserver.pipeline.xencenter.* properties([ From 90bcef37e8dbb4e7bd64619c0a025fea6d8a6273 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Wed, 1 Nov 2023 10:30:03 +0800 Subject: [PATCH 24/31] CA-384579: Call previous NRPE plugin xapi to resolve certs permission issue --- .../Actions/NRPE/NRPEHostConfiguration.cs | 1 + XenModel/Actions/NRPE/NRPEUpdateAction.cs | 24 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs index 31154b329f..c9668a98ac 100644 --- a/XenModel/Actions/NRPE/NRPEHostConfiguration.cs +++ b/XenModel/Actions/NRPE/NRPEHostConfiguration.cs @@ -44,6 +44,7 @@ public class NRPEHostConfiguration : ICloneable, IEquatable enableDict = new Dictionary + { + { "enable", "true" } + }; + try + { + string controlResult = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, + NRPEHostConfiguration.XAPI_NRPE_CONTROL, enableDict); + log.InfoFormat("Run NRPE {0}, return: {1}", NRPEHostConfiguration.XAPI_NRPE_CONTROL, controlResult); + } + catch (Exception e) + { + log.ErrorFormat("Run NRPE {0} failed, error: {1}", NRPEHostConfiguration.XAPI_NRPE_CONTROL, e.Message); + } + } + string nrpeUpdateStatusMethod = enableNRPE ? NRPEHostConfiguration.XAPI_NRPE_ENABLE : NRPEHostConfiguration.XAPI_NRPE_DISABLE; string result = Host.call_plugin(host.Connection.Session, host.opaque_ref, NRPEHostConfiguration.XAPI_NRPE_PLUGIN_NAME, From eda68f60cfc3bcd38db475cda4ccc9e90c9beb67 Mon Sep 17 00:00:00 2001 From: Bengang Yuan Date: Thu, 2 Nov 2023 10:15:43 +0800 Subject: [PATCH 25/31] CA-384629: NRPE threshold check label mistake --- XenModel/Messages.Designer.cs | 4 ++-- XenModel/Messages.resx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index ec1a7419f9..f711beda2c 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29250,7 +29250,7 @@ public static string NRPE_CHECK_SWAP { } /// - /// Looks up a localized string similar to Host vGPU Memory Usage (%). + /// Looks up a localized string similar to Host vGPU Usage (%). /// public static string NRPE_CHECK_VGPU { get { @@ -29259,7 +29259,7 @@ public static string NRPE_CHECK_VGPU { } /// - /// Looks up a localized string similar to Host vGPU Usage (%). + /// Looks up a localized string similar to Host vGPU Memory Usage (%). /// public static string NRPE_CHECK_VGPU_MEMORY { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index be0c523ec2..d57e0d173c 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10150,10 +10150,10 @@ When you configure an NFS storage repository, you simply provide the host name o Dom0 Free Swap (%) - Host vGPU Memory Usage (%) + Host vGPU Usage (%) - Host vGPU Usage (%) + Host vGPU Memory Usage (%) NRPE Configuration From 3b773c738f8528dcaa63be58fffbb5f793885260 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Tue, 14 Nov 2023 13:25:34 +0000 Subject: [PATCH 26/31] CA-383483: Rewrote the migration logic to fix regression (#3241) * Simplified the class name by renaming CrossPoolMigrateCanMigrateFilter to CrossPoolMigrateFilter. * CA-383483: Rewrote (again) the migration logic because the fix to CA-294370 regressed migration from local to local storage. Also, minor refactoring to some methods for more efficient calculations. Signed-off-by: Konstantina Chremmou --- XenAdmin/Commands/CrossPoolMigrateCommand.cs | 14 +- XenAdmin/Commands/VMOperationHostCommand.cs | 62 ++++-- .../CrossPoolMigrateDestinationPage.cs | 4 +- ...ateFilter.cs => CrossPoolMigrateFilter.cs} | 209 +++++++++--------- XenAdmin/XenAdmin.csproj | 2 +- 5 files changed, 159 insertions(+), 132 deletions(-) rename XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/{CrossPoolMigrateCanMigrateFilter.cs => CrossPoolMigrateFilter.cs} (52%) diff --git a/XenAdmin/Commands/CrossPoolMigrateCommand.cs b/XenAdmin/Commands/CrossPoolMigrateCommand.cs index 66838cec16..bd66d6f68d 100644 --- a/XenAdmin/Commands/CrossPoolMigrateCommand.cs +++ b/XenAdmin/Commands/CrossPoolMigrateCommand.cs @@ -119,14 +119,16 @@ public static bool CanRun(VM vm, Host preselectedHost, out string failureReason, return false; } - var vms = new List {vm}; + if (preselectedHost != null) + { + var vms = new List {vm}; - if (preselectedHost != null && new ResidentHostIsSameAsSelectionFilter(preselectedHost, vms).FailureFound(out failureReason)) - return false; + if (new ResidentHostIsSameAsSelectionFilter(preselectedHost, vms).FailureFound(out failureReason)) + return false; - if (preselectedHost != null && new CrossPoolMigrateCanMigrateFilter(preselectedHost, new List {vm}, - WizardMode.Migrate, cache).FailureFound(out failureReason)) - return false; + if (new CrossPoolMigrateFilter(preselectedHost, vms, WizardMode.Migrate, cache).FailureFound(out failureReason)) + return false; + } failureReason = string.Empty; return true; diff --git a/XenAdmin/Commands/VMOperationHostCommand.cs b/XenAdmin/Commands/VMOperationHostCommand.cs index dd7a1ba445..ef74a0779e 100644 --- a/XenAdmin/Commands/VMOperationHostCommand.cs +++ b/XenAdmin/Commands/VMOperationHostCommand.cs @@ -46,7 +46,7 @@ internal class VMOperationHostCommand : VMOperationCommand { public delegate Host GetHostForVM(VM vm); - private readonly static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary _cantBootReasons = new Dictionary(); private readonly bool _noneCanBoot = true; private readonly string _text; @@ -65,9 +65,7 @@ public VMOperationHostCommand(IMainWindow mainWindow, IEnumerable { VM vm = (VM)item.XenObject; - string reason = GetVmCannotBootOnHostReason(vm, GetHost(vm), session, operation); - - if (reason == null) + if (VmCanBootOnHost(vm, GetHost(vm), session, operation, out var reason)) _noneCanBoot = false; else _cantBootReasons[vm] = reason; @@ -107,26 +105,38 @@ protected override bool CanRun(VM vm) return vm != null && !_cantBootReasons.ContainsKey(vm); } - internal static string GetVmCannotBootOnHostReason(VM vm, Host host, Session session, vm_operations operation) + internal static bool VmCanBootOnHost(VM vm, Host host, Session session, vm_operations operation, out string cannotBootReason) { - Host residentHost = vm.Connection.Resolve(vm.resident_on); - if (host == null) - return Messages.NO_HOME_SERVER; + { + cannotBootReason = Messages.NO_HOME_SERVER; + return false; + } - if (vm.power_state == vm_power_state.Running && residentHost != null - && Helpers.ProductVersionCompare(Helpers.HostProductVersion(host), Helpers.HostProductVersion(residentHost)) < 0) + if (vm.power_state == vm_power_state.Running) { - // This will be a migrate menu if powerstate if running - return Messages.OLDER_THAN_CURRENT_SERVER; + var residentHost = vm.Connection.Resolve(vm.resident_on); + + if (residentHost != null) + { + if (host.opaque_ref == residentHost.opaque_ref) + { + cannotBootReason = Messages.HOST_MENU_CURRENT_SERVER; + return false; + } + + if (Helpers.ProductVersionCompare(Helpers.HostProductVersion(host), Helpers.HostProductVersion(residentHost)) < 0) + { + cannotBootReason = Messages.OLDER_THAN_CURRENT_SERVER; + return false; + } + } } - - if (vm.power_state == vm_power_state.Running && residentHost != null && host.opaque_ref == residentHost.opaque_ref) - return Messages.HOST_MENU_CURRENT_SERVER; if ((operation == vm_operations.pool_migrate || operation == vm_operations.resume_on) && VmCpuIncompatibleWithHost(host, vm)) { - return FriendlyErrorNames.VM_INCOMPATIBLE_WITH_THIS_HOST; + cannotBootReason = FriendlyErrorNames.VM_INCOMPATIBLE_WITH_THIS_HOST; + return false; } try @@ -137,20 +147,27 @@ internal static string GetVmCannotBootOnHostReason(VM vm, Host host, Session ses { if (f.ErrorDescription.Count > 2 && f.ErrorDescription[0] == Failure.VM_REQUIRES_SR) { - SR sr = host.Connection.Resolve((new XenRef(f.ErrorDescription[2]))); + SR sr = host.Connection.Resolve(new XenRef(f.ErrorDescription[2])); if (sr != null && sr.content_type == SR.Content_Type_ISO) - return Messages.MIGRATE_PLEASE_EJECT_YOUR_CD; + { + cannotBootReason = Messages.MIGRATE_PLEASE_EJECT_YOUR_CD; + return false; + } } - return f.ShortMessage; + + cannotBootReason = f.ShortMessage; + return false; } catch (Exception e) { log.ErrorFormat("There was an error calling assert_can_boot_here on host {0}: {1}", host.Name(), e.Message); - return Messages.HOST_MENU_UNKNOWN_ERROR; + cannotBootReason = Messages.HOST_MENU_UNKNOWN_ERROR; + return false; } - return null; + cannotBootReason = null; + return true; } protected override CommandErrorDialog GetErrorDialogCore(IDictionary cantRunReasons) @@ -160,8 +177,7 @@ protected override CommandErrorDialog GetErrorDialogCore(IDictionary { new ResidentHostIsSameAsSelectionFilter(xenItem, selectedVMs), - new CrossPoolMigrateCanMigrateFilter(xenItem, selectedVMs, wizardMode, migrateFilterCache) + new CrossPoolMigrateFilter(xenItem, selectedVMs, wizardMode, migrateFilterCache) }; return new DelayLoadingOptionComboBoxItem(xenItem, filters); } @@ -139,7 +139,7 @@ protected override List CreateTargetServerFilterList(IXenObject vmList.Add(selectedVMs.Find(vm => vm.opaque_ref == opaqueRef)); filters.Add(new ResidentHostIsSameAsSelectionFilter(xenObject, vmList)); - filters.Add(new CrossPoolMigrateCanMigrateFilter(xenObject, vmList, wizardMode, migrateFilterCache)); + filters.Add(new CrossPoolMigrateFilter(xenObject, vmList, wizardMode, migrateFilterCache)); } return filters; diff --git a/XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateCanMigrateFilter.cs b/XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateFilter.cs similarity index 52% rename from XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateCanMigrateFilter.cs rename to XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateFilter.cs index 604fda6ef3..2e64a8a6f0 100644 --- a/XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateCanMigrateFilter.cs +++ b/XenAdmin/Wizards/CrossPoolMigrateWizard/Filters/CrossPoolMigrateFilter.cs @@ -38,16 +38,16 @@ namespace XenAdmin.Wizards.CrossPoolMigrateWizard.Filters { - public class CrossPoolMigrateCanMigrateFilter : ReasoningFilter + public class CrossPoolMigrateFilter : ReasoningFilter { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly WizardMode _wizardMode; private readonly List _preSelectedVMs; - private Dictionary> _cache; + private readonly Dictionary> _cache; private bool _canceled; private static readonly object _cacheLock = new object(); - public CrossPoolMigrateCanMigrateFilter(IXenObject itemAddedToFilterOn, List preSelectedVMs, WizardMode wizardMode, Dictionary> cache = null) + public CrossPoolMigrateFilter(IXenObject itemAddedToFilterOn, List preSelectedVMs, WizardMode wizardMode, Dictionary> cache = null) : base(itemAddedToFilterOn) { _wizardMode = wizardMode; @@ -90,109 +90,71 @@ protected override bool FailureFoundFor(IXenObject itemToFilterOn, out string fa } } - var hostMemoryUnavailableFailures = 0; foreach (Host host in targets) { if (_canceled) return false; - if (vmCache.TryGetValue(host.opaque_ref, out var reason) && !string.IsNullOrEmpty(reason)) + if (vmCache.TryGetValue(host.opaque_ref, out var reason)) { - failureReason = reason; + if (!string.IsNullOrEmpty(reason)) + failureReason = reason; continue; } - try - { - //Skip the resident host as there's a filter for it and - //if not then you could exclude intrapool migration - //CA-205799: do not offer the host the VM is currently on - Host homeHost = vm.Home(); - if (homeHost != null && homeHost.opaque_ref == host.opaque_ref) - continue; - - //if pool_migrate can be done, then we will allow it in the wizard, even if storage migration is not allowed (i.e. users can use the wizard to live-migrate a VM inside the pool) - if (_wizardMode == WizardMode.Migrate && vmPool != null && targetPool != null && vmPool.opaque_ref == targetPool.opaque_ref) - { - failureReason = VMOperationHostCommand.GetVmCannotBootOnHostReason(vm, host, vm.Connection.Session, vm_operations.pool_migrate); - - if (string.IsNullOrEmpty(failureReason)) - break; - else - continue; - } - - //check if the destination host is older than the source host - var destinationVersion = Helpers.HostPlatformVersion(host); - var sourceVersion = Helpers.HostPlatformVersion(vm.Home() ?? Helpers.GetCoordinator(vmPool)); - - if (Helpers.ProductVersionCompare(destinationVersion, sourceVersion) < 0) - { - failureReason = Messages.OLDER_THAN_CURRENT_SERVER; - continue; - } - - if (Host.RestrictDMC(host) && - (vm.power_state == vm_power_state.Running || - vm.power_state == vm_power_state.Paused || - vm.power_state == vm_power_state.Suspended) && - (vm.memory_static_min > vm.memory_dynamic_min || //corner case, probably unlikely - vm.memory_dynamic_min != vm.memory_dynamic_max || - vm.memory_dynamic_max != vm.memory_static_max)) - { - failureReason = FriendlyErrorNames.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE; - continue; - } - - PIF managementPif = host.Connection.Cache.PIFs.First(p => p.management); - XenAPI.Network managementNetwork = host.Connection.Cache.Resolve(managementPif.network); - - Session session = host.Connection.DuplicateSession(); - Dictionary receiveMapping = Host.migrate_receive(session, host.opaque_ref, managementNetwork.opaque_ref, new Dictionary()); - - var targetSrs = host.Connection.Cache.SRs.Where(sr => sr.SupportsStorageMigration()).ToList(); - var targetNetwork = GetANetwork(host); + //CA-205799: do not offer the host the VM is currently on + Host homeHost = vm.Home(); + if (homeHost != null && homeHost.opaque_ref == host.opaque_ref) + continue; - VM.assert_can_migrate(vm.Connection.Session, - vm.opaque_ref, - receiveMapping, - true, - GetVdiMap(vm, targetSrs), - vm.Connection == host.Connection ? new Dictionary, XenRef>() : GetVifMap(vm, targetNetwork), - new Dictionary()); + //check if the destination host is older than the source host + var destinationVersion = Helpers.HostPlatformVersion(host); + var sourceVersion = Helpers.HostPlatformVersion(vm.Home() ?? Helpers.GetCoordinator(vmPool)); - break; + if (Helpers.ProductVersionCompare(destinationVersion, sourceVersion) < 0) + { + failureReason = Messages.OLDER_THAN_CURRENT_SERVER; + continue; } - catch (Failure failure) + + if (Host.RestrictDMC(host) && + (vm.power_state == vm_power_state.Running || + vm.power_state == vm_power_state.Paused || + vm.power_state == vm_power_state.Suspended) && + (vm.memory_static_min > vm.memory_dynamic_min || //corner case, probably unlikely + vm.memory_dynamic_min != vm.memory_dynamic_max || + vm.memory_dynamic_max != vm.memory_static_max)) { - // CA-359124 VM is migratable if a snapshot has more VIFs than the VM. As long as the mapping takes this into account. - if (failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == Failure.VIF_NOT_IN_MAP && - SnapshotsContainExtraVIFs(vm)) - break; - - if (failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) - failureReason = failure.Message.Split('\n')[0].TrimEnd('\r'); // we want the first line only - else if (failure.ErrorDescription.Count > 1 && failure.ErrorDescription[1].Contains(Failure.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE)) - failureReason = FriendlyErrorNames.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE; - // CA-378758: Ensure all hosts in pool hit `HOST_NOT_ENOUGH_FREE_MEMORY` before preventing migration - else if (!failure.ErrorDescription.Contains(Failure.HOST_NOT_ENOUGH_FREE_MEMORY) || ++hostMemoryUnavailableFailures >= targets.Count) - failureReason = failure.Message; - - log.InfoFormat("VM {0} cannot be migrated to {1}. Reason: {2};", vm.Name(), host.Name(), failure.Message); + failureReason = FriendlyErrorNames.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE; + continue; } - catch (Exception e) + + if (CanDoStorageMigration(vm, host, out failureReason)) { - log.Error($"There was an error while asserting the VM {vm.Name()} can be migrated to {itemToFilterOn.Name()}:", e); - failureReason = Messages.HOST_MENU_UNKNOWN_ERROR; + lock (_cacheLock) + vmCache[host.opaque_ref] = null; + break; } - finally + + //if pool_migrate can be done, then we will allow it in the wizard, even if storage migration is not allowed + //(i.e. users can use the wizard to live-migrate a VM inside the pool) + + string reason2 = null; + + if (_wizardMode == WizardMode.Migrate && + vmPool != null && targetPool != null && vmPool.opaque_ref == targetPool.opaque_ref && + VMOperationHostCommand.VmCanBootOnHost(vm, host, vm.Connection.Session, vm_operations.pool_migrate, out reason2)) { lock (_cacheLock) - { - if (!string.IsNullOrEmpty(failureReason)) - vmCache[host.opaque_ref] = failureReason; - } + vmCache[host.opaque_ref] = null; + break; } + + if (!string.IsNullOrEmpty(reason2)) + failureReason += " - " + reason2; + + lock (_cacheLock) + vmCache[host.opaque_ref] = failureReason; } if (!string.IsNullOrEmpty(failureReason)) @@ -203,6 +165,55 @@ protected override bool FailureFoundFor(IXenObject itemToFilterOn, out string fa return false; } + private bool CanDoStorageMigration(VM vm, Host host, out string failureReason) + { + failureReason = null; + + try + { + PIF managementPif = host.Connection.Cache.PIFs.First(p => p.management); + XenAPI.Network managementNetwork = host.Connection.Cache.Resolve(managementPif.network); + + Session session = host.Connection.DuplicateSession(); + Dictionary receiveMapping = Host.migrate_receive(session, host.opaque_ref, managementNetwork.opaque_ref, new Dictionary()); + + var targetSrs = host.Connection.Cache.SRs.Where(sr => sr.SupportsStorageMigration()).ToList(); + var targetNetwork = GetANetwork(host); + + VM.assert_can_migrate(vm.Connection.Session, + vm.opaque_ref, + receiveMapping, + true, + GetVdiMap(vm, targetSrs), + vm.Connection == host.Connection ? new Dictionary, XenRef>() : GetVifMap(vm, targetNetwork), + new Dictionary()); + + return true; + } + catch (Failure failure) + { + // CA-359124 VM is migratable if a snapshot has more VIFs than the VM. As long as the mapping takes this into account. + if (failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == Failure.VIF_NOT_IN_MAP && SnapshotsContainExtraVIFs(vm)) + return true; + + if (failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) + failureReason = failure.Message.Split('\n')[0].TrimEnd('\r'); // we want the first line only + else if (failure.ErrorDescription.Count > 1 && failure.ErrorDescription[1].Contains(Failure.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE)) + failureReason = FriendlyErrorNames.DYNAMIC_MEMORY_CONTROL_UNAVAILABLE; + else + failureReason = failure.Message; + + log.InfoFormat("VM {0} cannot be migrated to {1}. Reason: {2};", vm.Name(), host.Name(), failure.Message); + return false; + } + catch (Exception e) + { + log.Error($"There was an error while asserting the VM {vm.Name()} can be migrated to {host.Name()}:", e); + failureReason = Messages.HOST_MENU_UNKNOWN_ERROR; + return false; + } + } + /// /// Check if a VM's snapshots contain a reference to a VIF not present in the VM. /// @@ -214,25 +225,23 @@ private static bool SnapshotsContainExtraVIFs(VM vm) return snapVIFs.Any(snapVIF => !vm.VIFs.Contains(snapVIF)); } - private List CollateHosts(IXenObject itemToFilterOn, out Pool thePool) + private List CollateHosts(IXenObject itemToFilterOn, out Pool targetPool) { - thePool = null; + targetPool = null; + var targetHosts = new List(); - List target = new List(); - if (itemToFilterOn is Host) + if (itemToFilterOn is Host host) { - target.Add(itemToFilterOn as Host); - thePool = Helpers.GetPoolOfOne(itemToFilterOn.Connection); + targetHosts.Add(host); + targetPool = Helpers.GetPoolOfOne(host.Connection); } - - if (itemToFilterOn is Pool) + else if (itemToFilterOn is Pool pool) { - Pool pool = itemToFilterOn as Pool; - target.AddRange(pool.Connection.Cache.Hosts); - target.Sort(); - thePool = pool; + targetHosts.AddRange(pool.Connection.Cache.Hosts); + targetHosts.Sort(); + targetPool = pool; } - return target; + return targetHosts; } private Dictionary, XenRef> GetVdiMap(VM vm, List targetSrs) diff --git a/XenAdmin/XenAdmin.csproj b/XenAdmin/XenAdmin.csproj index e17cbd15f3..6a936276a5 100755 --- a/XenAdmin/XenAdmin.csproj +++ b/XenAdmin/XenAdmin.csproj @@ -3790,7 +3790,7 @@ WlbReportSubscriptionDialog.cs - + UserControl From 22e1973023b0166db1581d8dc1bde35aed3682f3 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Tue, 14 Nov 2023 17:00:02 +0000 Subject: [PATCH 27/31] Corrected positioning of DVD ISO list control. Signed-off-by: Konstantina Chremmou --- XenAdmin/ConsoleView/VNCTabView.Designer.cs | 22 +-- XenAdmin/ConsoleView/VNCTabView.resx | 136 ++++++++---------- .../Controls/MultipleDvdIsoList.Designer.cs | 1 + XenAdmin/Controls/MultipleDvdIsoList.resx | 23 ++- 4 files changed, 93 insertions(+), 89 deletions(-) diff --git a/XenAdmin/ConsoleView/VNCTabView.Designer.cs b/XenAdmin/ConsoleView/VNCTabView.Designer.cs index 88e6d596ed..848fb7298f 100644 --- a/XenAdmin/ConsoleView/VNCTabView.Designer.cs +++ b/XenAdmin/ConsoleView/VNCTabView.Designer.cs @@ -57,6 +57,7 @@ private void InitializeComponent() this.fullscreenButton = new System.Windows.Forms.Button(); this.dockButton = new System.Windows.Forms.Button(); this.tip = new System.Windows.Forms.ToolTip(this.components); + this.toggleConsoleButton = new System.Windows.Forms.Button(); this.LifeCycleMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.powerStateLabel = new System.Windows.Forms.Label(); this.dedicatedGpuWarning = new System.Windows.Forms.Label(); @@ -64,7 +65,6 @@ private void InitializeComponent() this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.HostLabel = new System.Windows.Forms.Label(); this.buttonSSH = new System.Windows.Forms.Button(); - this.toggleConsoleButton = new System.Windows.Forms.Button(); this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.tableLayoutPanel1.SuspendLayout(); @@ -136,6 +136,14 @@ private void InitializeComponent() // this.tip.ShowAlways = true; // + // toggleConsoleButton + // + resources.ApplyResources(this.toggleConsoleButton, "toggleConsoleButton"); + this.toggleConsoleButton.Name = "toggleConsoleButton"; + this.tip.SetToolTip(this.toggleConsoleButton, resources.GetString("toggleConsoleButton.ToolTip")); + this.toggleConsoleButton.UseVisualStyleBackColor = true; + this.toggleConsoleButton.Click += new System.EventHandler(this.toggleConsoleButton_Click); + // // LifeCycleMenuStrip // this.LifeCycleMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); @@ -180,8 +188,8 @@ private void InitializeComponent() // // HostLabel // - this.HostLabel.AutoEllipsis = true; resources.ApplyResources(this.HostLabel, "HostLabel"); + this.HostLabel.AutoEllipsis = true; this.HostLabel.ForeColor = System.Drawing.Color.White; this.HostLabel.Name = "HostLabel"; // @@ -192,14 +200,6 @@ private void InitializeComponent() this.buttonSSH.UseVisualStyleBackColor = true; this.buttonSSH.Click += new System.EventHandler(this.buttonSSH_Click); // - // toggleConsoleButton - // - resources.ApplyResources(this.toggleConsoleButton, "toggleConsoleButton"); - this.toggleConsoleButton.Name = "toggleConsoleButton"; - this.tip.SetToolTip(this.toggleConsoleButton, resources.GetString("toggleConsoleButton.ToolTip")); - this.toggleConsoleButton.UseVisualStyleBackColor = true; - this.toggleConsoleButton.Click += new System.EventHandler(this.toggleConsoleButton_Click); - // // multipleDvdIsoList1 // resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1"); @@ -254,7 +254,6 @@ private void InitializeComponent() private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.ContextMenuStrip LifeCycleMenuStrip; private System.Windows.Forms.PictureBox pictureBox1; - private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1; private System.Windows.Forms.Label HostLabel; private System.Windows.Forms.Button toggleConsoleButton; private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1; @@ -263,5 +262,6 @@ private void InitializeComponent() private System.Windows.Forms.Button buttonSSH; private System.Windows.Forms.PictureBox pictureBoxGeneralInformationMessage; private System.Windows.Forms.Label labelGeneralInformationMessage; + private Controls.GradientPanel.HorizontalGradientPanel gradientPanel1; } } diff --git a/XenAdmin/ConsoleView/VNCTabView.resx b/XenAdmin/ConsoleView/VNCTabView.resx index 09cd837d7a..4e22ae94c4 100644 --- a/XenAdmin/ConsoleView/VNCTabView.resx +++ b/XenAdmin/ConsoleView/VNCTabView.resx @@ -199,7 +199,7 @@ NoControl - 223, 4 + 223, 2 0, 0, 3, 0 @@ -208,7 +208,7 @@ 0, 30 - 200, 26 + 205, 30 5 @@ -429,6 +429,42 @@ 17, 17 + + Left + + + False + + + NoControl + + + 525, 6 + + + 175, 24 + + + 3 + + + Looking for guest console... + + + Remote access is not enabled on this guest + + + toggleConsoleButton + + + System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + tableLayoutPanel2 + + + 2 + 81, 17 @@ -513,12 +549,12 @@ 5 + + Left + True - - Fill - Segoe UI, 11.25pt @@ -526,20 +562,17 @@ NoControl - 3, 0 + 3, 8 8, 0, 0, 0 - 8, 37 + 8, 20 0 - - MiddleLeft - HostLabel @@ -553,7 +586,7 @@ 0 - Top, Right + Left True @@ -565,13 +598,10 @@ NoControl - 399, 6 - - - 3, 6, 6, 6 + 397, 7 - 114, 23 + 122, 23 2 @@ -591,56 +621,20 @@ 1 - - Top, Right + + Left, Right - - False - - - NoControl - - - 522, 6 - - - 3, 6, 6, 6 - - - 175, 24 - - - 3 - - - Looking for guest console... - - - Remote access is not enabled on this guest - - - toggleConsoleButton - - - System.Windows.Forms.Button, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - tableLayoutPanel2 - - - 2 + + True - - Fill + + GrowAndShrink - 47, 3 - - - 3, 3, 12, 3 + 47, 5 - 337, 31 + 344, 27 1 @@ -649,7 +643,7 @@ multipleDvdIsoList1 - XenAdmin.Controls.MultipleDvdIsoList, XenCenterMain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.MultipleDvdIsoList, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null tableLayoutPanel2 @@ -657,26 +651,20 @@ 3 + + Left + None - - Fill - NoControl - 15, 1 - - - 1, 1, 1, 1 + 17, 6 - 28, 35 - - - CenterImage + 24, 24 8 @@ -730,7 +718,7 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="HostLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="buttonSSH" Row="0" RowSpan="1" Column="3" ColumnSpan="1" /><Control Name="toggleConsoleButton" Row="0" RowSpan="1" Column="5" ColumnSpan="1" /><Control Name="multipleDvdIsoList1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="pictureBox1" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,AutoSize,0" /><Rows Styles="Percent,100,Absolute,100" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="HostLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="buttonSSH" Row="0" RowSpan="1" Column="3" ColumnSpan="1" /><Control Name="toggleConsoleButton" Row="0" RowSpan="1" Column="5" ColumnSpan="1" /><Control Name="multipleDvdIsoList1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="pictureBox1" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0,AutoSize,0" /><Rows Styles="Percent,100,Absolute,37" /></TableLayoutSettings> Top @@ -748,7 +736,7 @@ gradientPanel1 - XenAdmin.Controls.GradientPanel.GradientPanel, XenCenterMain, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + XenAdmin.Controls.GradientPanel.HorizontalGradientPanel, [XenCenter], Version=0.0.0.0, Culture=neutral, PublicKeyToken=null $this diff --git a/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs b/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs index 048d614f53..fbdb877e96 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs +++ b/XenAdmin/Controls/MultipleDvdIsoList.Designer.cs @@ -98,6 +98,7 @@ private void InitializeComponent() this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); } diff --git a/XenAdmin/Controls/MultipleDvdIsoList.resx b/XenAdmin/Controls/MultipleDvdIsoList.resx index 38965f8799..455c813df9 100644 --- a/XenAdmin/Controls/MultipleDvdIsoList.resx +++ b/XenAdmin/Controls/MultipleDvdIsoList.resx @@ -159,6 +159,12 @@ True + + True + + + GrowAndShrink + 4 @@ -259,7 +265,7 @@ 2 - 672, 77 + 672, 64 0 @@ -277,7 +283,7 @@ 0 - <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelSingleDvd" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="comboBoxDrive" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="cdChanger1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="linkLabelEject" Row="0" RowSpan="1" Column="3" ColumnSpan="1" /><Control Name="newCDLabel" Row="1" RowSpan="1" Column="0" ColumnSpan="4" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0" /><Rows Styles="AutoSize,0,Percent,100" /></TableLayoutSettings> + <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="labelSingleDvd" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="comboBoxDrive" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="cdChanger1" Row="0" RowSpan="1" Column="2" ColumnSpan="1" /><Control Name="linkLabelEject" Row="0" RowSpan="1" Column="3" ColumnSpan="1" /><Control Name="newCDLabel" Row="1" RowSpan="1" Column="0" ColumnSpan="4" /></Controls><Columns Styles="AutoSize,0,AutoSize,0,Percent,100,AutoSize,0" /><Rows Styles="AutoSize,0,AutoSize,0" /></TableLayoutSettings> Microsoft Sans Serif, 8.25pt, style=Bold, Underline @@ -286,7 +292,10 @@ NoControl - 3, 45 + 3, 39 + + + 3, 12, 3, 12 666, 13 @@ -321,8 +330,14 @@ 96, 96 + + True + + + GrowAndShrink + - 672, 77 + 672, 64 MultipleDvdIsoList From b9cb2d34f19516f3819cec916cd2e6844b224cd3 Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 15 Nov 2023 15:54:56 +0000 Subject: [PATCH 28/31] Removed hardcoded application name. Signed-off-by: Konstantina Chremmou --- XenModel/Messages.Designer.cs | 2 +- XenModel/Messages.resx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/XenModel/Messages.Designer.cs b/XenModel/Messages.Designer.cs index d580f79aa5..c0853ba248 100755 --- a/XenModel/Messages.Designer.cs +++ b/XenModel/Messages.Designer.cs @@ -29340,7 +29340,7 @@ public static string NRPE_METRIC_TOOLTIP { } /// - /// Looks up a localized string similar to Failed to retrieve NRPE configuration, please check XenCenter logs.. + /// Looks up a localized string similar to Failed to retrieve NRPE configuration, please check the application logs.. /// public static string NRPE_RETRIEVE_FAILED { get { diff --git a/XenModel/Messages.resx b/XenModel/Messages.resx index 865d0ea2ce..7ed952b91f 100755 --- a/XenModel/Messages.resx +++ b/XenModel/Messages.resx @@ -10180,7 +10180,7 @@ When you configure an NFS storage repository, you simply provide the host name o NRPE check name: {0} - Failed to retrieve NRPE configuration, please check XenCenter logs. + Failed to retrieve NRPE configuration, please check the application logs. Retrieving NRPE configuration... From 01a831f3c40ab9c32b3de1cb9b9954f931bced5b Mon Sep 17 00:00:00 2001 From: Konstantina Chremmou Date: Wed, 15 Nov 2023 15:55:47 +0000 Subject: [PATCH 29/31] CP-46393: Bumped branding library to v5.4. Signed-off-by: Konstantina Chremmou --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 452c8e03a8..c448a645c7 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -30,7 +30,7 @@ * SUCH DAMAGE. */ -def XENADMIN_BRANDING_TAG = 'v5.3' +def XENADMIN_BRANDING_TAG = 'v5.4' @Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.11"]) import com.xenserver.pipeline.xencenter.* From 4996f567bc25ccac615c97a96e616a9070d59779 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Thu, 16 Nov 2023 13:58:46 +0000 Subject: [PATCH 30/31] CA-385151: Fix skipped `MsiRMFilesInUse` patch The patch was skipped, and the "Launch XenCenter" button did not show anymore. This was because the custom property `XS_WixUIRMPressedOk` is defined within the patch. Signed-off-by: Danilo Del Busso --- WixInstaller/wix_src.patch | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/WixInstaller/wix_src.patch b/WixInstaller/wix_src.patch index 863068f4c6..e0193bcaac 100644 --- a/WixInstaller/wix_src.patch +++ b/WixInstaller/wix_src.patch @@ -1007,7 +1007,7 @@ diff -ru wixlib/ExitDialog.wxl wixlib/ExitDialog.wxl + -diff --git wixlib/MsiRMFilesInUse.wxs wixlib/MsiRMFilesInUse.wxs +diff -ru wixlib/MsiRMFilesInUse.wxs wixlib/MsiRMFilesInUse.wxs --- wixlib/MsiRMFilesInUse.wxs +++ wixlib/MsiRMFilesInUse.wxs @@ -6,10 +6,13 @@ @@ -1024,4 +1024,3 @@ diff --git wixlib/MsiRMFilesInUse.wxs wixlib/MsiRMFilesInUse.wxs 1 - \ No newline at end of file From 903bc9149dc65b460422d691002a377c92181a09 Mon Sep 17 00:00:00 2001 From: Danilo Del Busso Date: Thu, 16 Nov 2023 14:04:40 +0000 Subject: [PATCH 31/31] CP-45516: Bump pipeline to `v4.12` Signed-off-by: Danilo Del Busso --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 452c8e03a8..5b9010eb50 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -32,7 +32,7 @@ def XENADMIN_BRANDING_TAG = 'v5.3' -@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.11"]) +@Library(['PacmanSharedLibrary', "xencenter-pipeline@v4.12"]) import com.xenserver.pipeline.xencenter.* properties([