diff --git a/XenModel/XenAPI-Extensions/VM.cs b/XenModel/XenAPI-Extensions/VM.cs
index 7915be1e7..d5e578bf4 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();
}
///