Exemple #1
0
		public ImportVmAction(IXenConnection connection, Host affinity, string filename, SR sr)
			: base(connection, string.Format(Messages.IMPORTVM_TITLE, filename, Helpers.GetName(connection)), Messages.IMPORTVM_PREP)
		{
			Pool = Helpers.GetPoolOfOne(connection);
			m_affinity = affinity;
			Host = affinity ?? connection.Resolve(Pool.master);
			SR = sr;
			VM = null;
			m_filename = filename;

			#region RBAC Dependencies

			ApiMethodsToRoleCheck.AddRange(ConstantRBACRequirements);

			if (affinity != null)
				ApiMethodsToRoleCheck.Add("vm.set_affinity");

			//??
			//if (startAutomatically)
			//	ApiMethodsToRoleCheck.Add("vm.start");

			ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList);
			ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList);

			#endregion
		}
 public VdiOpenDatabaseAction(IXenConnection connection, VDI vdi)
     : base(connection, String.Format(Messages.ACTION_VDI_OPEN_DATABASE_TITLE, connection.Resolve(vdi.SR).Name))
 {
     _vdi = vdi;
     #region RBAC Dependencies
     ApiMethodsToRoleCheck.Add("VDI.open_database");
     ApiMethodsToRoleCheck.Add("Session.get_record");
     #endregion
 }
Exemple #3
0
        private static void UpdateEmptyFolders(IXenConnection connection)
        {
            InvokeHelper.AssertOnEventThread();

            String[] emptyFolders = GetEmptyFolders(connection);

            Folder root = connection.Resolve(new XenRef <Folder>(PATH_SEPARATOR));

            if (root != null)
            {
                PurgeEmptyFolders(emptyFolders, root);
            }

            foreach (String path in emptyFolders)
            {
                GetOrCreateFolder(connection, path);
            }
        }
        private static bool HasPoolSharedStorage(IXenConnection conn)
        {
            if (conn == null)
            {
                return(false);
            }

            foreach (var pbd in conn.Cache.PBDs.Where(thePbd => thePbd.SR != null))
            {
                var sr = conn.Resolve(pbd.SR);

                if (sr != null && sr.SupportsVdiCreate() && sr.shared)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #5
0
 private Action <Session> ActionDelegate(bool autostartValue)
 {
     return(delegate(Session session)
     {
         var vm = _connection.Resolve(_VMref);
         var vmclone = (VM)vm.Clone();
         vm.Locked = true;
         vmclone.SetAutoPowerOn(autostartValue);
         try
         {
             vmclone.SaveChanges(session);
         }
         finally
         {
             vm.Locked = false;
         }
     });
 }
Exemple #6
0
        private void UpdateButtons()
        {
            label1.Visible             = false;
            Lun_Size_Different.Visible = false;
            if (comboBoxLun.Text != "" && comboBoxLun.Text != null)
            {
                origin_lun_text = comboBoxLun.Text.Substring(comboBoxLun.Text.LastIndexOf(":") + 1);
                if (_sr.other_config["mirror_iscsi_size"] != origin_lun_text)
                {
                    Lun_Size_Different.Visible = true;
                    buttonAdd.Enabled          = false;
                }
            }
            if (!IsLunInUse() && _sr.other_config["mirror_iscsi_size"] == origin_lun_text)
            {
                buttonAdd.Enabled = true;
            }
            foreach (XenRef <PBD> p in _sr.PBDs)
            {
                if (Connection.Resolve <PBD>(p).device_config.ContainsKey("SCSIid1"))
                {
                    if (Connection.Resolve <PBD>(p).device_config["SCSIid1"] != "")
                    {
                        origin_lun = Connection.Resolve <PBD>(p).device_config["SCSIid1"];
                    }
                }
                if (Connection.Resolve <PBD>(p).device_config.ContainsKey("SCSIid2"))
                {
                    if (Connection.Resolve <PBD>(p).device_config["SCSIid2"] != "")
                    {
                        origin_lun = Connection.Resolve <PBD>(p).device_config["SCSIid2"];
                    }
                }
            }
            if (comboBoxLun.Text != "")
            {
                int start = comboBoxLun.Text.LastIndexOf("(");
                int end   = comboBoxLun.Text.LastIndexOf(")");
                if (comboBoxLun.Text.Substring(start + 1, end - start - 1) == origin_lun)
                {
                    buttonAdd.Enabled = false;
                    label1.Visible    = true;
                }
            }
            UInt16 i;
            bool   portValid = UInt16.TryParse(textBoxIscsiPort.Text, out i);

            scanTargetHostButton.Enabled =
                !String.IsNullOrEmpty(getIscsiHost()) &&
                portValid;
        }
Exemple #7
0
        private static void CheckAndPlugPBDsFor(IXenConnection connection, List <XenRef <VM> > vmRefs, PlugMode plugMode)
        {
            //Program.AssertOffEventThread();

            List <VM> vms = new List <VM>();

            foreach (XenRef <VM> vmRef in vmRefs)
            {
                VM vm = null;
                while ((vm = connection.Resolve <VM>(vmRef)) == null)
                {
                    Thread.Sleep(100);
                }

                vms.Add(vm);
            }

            CheckAndPlugPBDsFor(vms, plugMode);
        }
Exemple #8
0
        public void UpdateDetails()
        {
            SR sr = _connection.Resolve(Disk.SR);

            if (sr == null)
            {
                SizeCell.Value   = Util.DiskSizeString(Disk.virtual_size);
                SrCell.Value     = Messages.NEWVMWIZARD_STORAGEPAGE_NOSTORAGE;
                SharedCell.Value = "";
            }
            else
            {
                SizeCell.Value   = sr.HBALunPerVDI() ? string.Empty : Util.DiskSizeString(Disk.virtual_size);
                SrCell.Value     = Helpers.GetName(sr);
                SharedCell.Value = sr.shared ? Messages.TRUE : Messages.FALSE;
            }

            NameCell.Value = Helpers.GetName(Disk);
        }
Exemple #9
0
        protected T TryResolveWithTimeout <T>(XenRef <T> t) where T : XenObject <T>
        {
            T   obj;
            int timeout = 120; // two minutes;

            while (timeout > 0)
            {
                obj = Connection.Resolve(t);
                if (obj != null)
                {
                    return(obj);
                }

                Thread.Sleep(1000);
                timeout = timeout - 1;
            }

            throw new Failure(new List <String>(new String[] { Failure.HANDLE_INVALID, t.opaque_ref }));
        }
Exemple #10
0
        public NewDiskDialog(IXenConnection connection, VM vm, SrPicker.SRPickerType PickerUsage, VDI diskTemplate, Host affinity, bool canResize, long minSize, IEnumerable <VDI> vdiNamesInUse)
            : this(connection, vdiNamesInUse)
        {
            TheVM            = vm;
            DiskTemplate     = diskTemplate;
            CanResize        = canResize;
            MinSize          = minSize;
            this.PickerUsage = PickerUsage;
            SrListBox.SetAffinity(affinity);

            Pool pool_sr = Helpers.GetPoolOfOne(connection);

            if (pool_sr != null)
            {
                SrListBox.DefaultSR = connection.Resolve(pool_sr.default_SR); //if default sr resolves to null the first sr in the list will be selected
            }
            SrListBox.selectDefaultSROrAny();

            LoadValues();
        }
Exemple #11
0
        private void AddStorageMappings(ref List <SummaryDetails> decoratedSummary)
        {
            foreach (var pair in mapping.Storage)
            {
                VDI vdi = connection.Resolve(new XenRef <VDI>(pair.Key));
                if (vdi == null)
                {
                    continue;
                }

                string valueToAdd = vdi.Name + separatorText + pair.Value.Name;

                if (pair.Key == mapping.Storage.First().Key)
                {
                    decoratedSummary.Add(new SummaryDetails(Messages.CPM_SUMMARY_KEY_STORAGE, valueToAdd));
                }
                else
                {
                    decoratedSummary.Add(new SummaryDetails(String.Empty, valueToAdd));
                }
            }
        }
Exemple #12
0
        private string ResolveLabel()
        {
            if (mapping.XenRef is XenRef <Host> )
            {
                Host targetHost = connection.Resolve(mapping.XenRef as XenRef <Host>);

                if (targetHost == null)
                {
                    return(Messages.UNKNOWN);
                }

                Pool targetPool = Helpers.GetPool(targetHost.Connection);
                if (targetPool != null)
                {
                    return(targetPool.Name);
                }

                return(mapping.TargetName);
            }

            return(mapping.TargetName);
        }
        protected T TryResolveWithTimeout <T>(XenRef <T> t) where T : XenObject <T>
        {
            log.DebugFormat("Resolving {0} {1}", t, t.opaque_ref);
            int timeout = 120; // two minutes;

            while (timeout > 0)
            {
                T obj = Connection.Resolve(t);
                if (obj != null)
                {
                    return(obj);
                }

                Thread.Sleep(1000);
                timeout = timeout - 1;
            }

            if (typeof(T) == typeof(Host))
            {
                throw new Failure(Failure.HOST_OFFLINE);
            }
            throw new Failure(Failure.HANDLE_INVALID, typeof(T).Name, t.opaque_ref);
        }
 private Action <Session> ActionDelegate(bool autostartValue)
 {
     return(delegate(Session session)
     {
         var vm = _connection.Resolve(_VMref);
         var vmclone = (VM)vm.Clone();
         vm.Locked = true;
         vmclone.SetAutoPowerOn(autostartValue);
         try
         {
             vmclone.SaveChanges(session);
         }
         finally
         {
             vm.Locked = false;
         }
         int wait = 5000;            // wait up to 5 seconds for the cache to be updated
         while (wait > 0 && vm.GetAutoPowerOn() != autostartValue)
         {
             Thread.Sleep(100);
             wait -= 100;
         }
     });
 }
Exemple #15
0
        private static Folder GetOrCreateFolder(IXenConnection connection, String[] path, int i)
        {
            if(i < 0)
                return null;

            XenRef<Folder> pathToPoint = new XenRef<Folder>(PathToPoint(path, i));

            Folder folder = connection.Resolve(pathToPoint);
            if (folder != null)
                return folder;

            Folder parent = GetOrCreateFolder(connection, path, i - 1);

            String name = i - 1 >= 0 ? path[i - 1] : String.Empty;
            Folder _folder = new Folder(parent, name);
            _folder.Path = (parent == null ? "" : parent.opaque_ref);
            _folder.opaque_ref = pathToPoint.opaque_ref;
            _folder.Connection = connection;

            if(parent != null)
                parent.AddObject(_folder);

            connection.Cache.AddFolder(pathToPoint, _folder);

            return _folder;
        }
Exemple #16
0
        private static void UpdateEmptyFolders(IXenConnection connection)
        {
            InvokeHelper.AssertOnEventThread();

            String[] emptyFolders = GetEmptyFolders(connection);

            Folder root = connection.Resolve(new XenRef<Folder>(PATH_SEPARATOR));
            if (root != null)
                PurgeEmptyFolders(emptyFolders, root);

            foreach (String path in emptyFolders)
                GetOrCreateFolder(connection, path);
        }
Exemple #17
0
        /// <summary>
        /// Tries to find the best SR for the given VDI considering first the
        /// suggestedSR then the pool's default SR, then other SRs.
        /// </summary>
        /// <returns>The SR if a suitable one is found, otherwise null</returns>
        private SR GetBestDiskStorage(IXenConnection connection, long diskSize, Host affinity, SR suggestedSr,
                                      out Image icon, out string tooltip)
        {
            icon    = Images.StaticImages._000_VirtualStorage_h32bit_16;
            tooltip = null;
            var sb = new StringBuilder();

            var suggestedSrVisible  = suggestedSr != null && suggestedSr.CanBeSeenFrom(affinity);
            var suggestedSrHasSpace = suggestedSr != null && suggestedSr.VdiCreationCanProceed(diskSize);

            if (suggestedSrVisible && suggestedSrHasSpace)
            {
                return(suggestedSr);
            }

            if (suggestedSrVisible)
            {
                sb.AppendFormat(Messages.NEWVMWIZARD_STORAGEPAGE_SUGGESTED_NOSPACE, suggestedSr.Name().Ellipsise(50)).AppendLine();
            }
            else if (suggestedSrHasSpace)
            {
                sb.AppendFormat(Affinity == null
                        ? Messages.NEWVMWIZARD_STORAGEPAGE_SUGGESTED_LOCAL_NO_HOME
                        : Messages.NEWVMWIZARD_STORAGEPAGE_SUGGESTED_LOCAL,
                                suggestedSr.Name().Ellipsise(50)).AppendLine();
            }

            SR  defaultSr         = connection.Resolve(Helpers.GetPoolOfOne(connection).default_SR);
            var defaultSrVisible  = defaultSr != null && defaultSr.CanBeSeenFrom(affinity);
            var defaultSrHasSpace = defaultSr != null && defaultSr.VdiCreationCanProceed(diskSize);

            if (defaultSrVisible && defaultSrHasSpace)
            {
                if (suggestedSr != null)
                {
                    sb.AppendLine(Messages.NEWVMWIZARD_STORAGEPAGE_XC_SELECTION);
                    tooltip = sb.ToString();
                    icon    = Images.StaticImages._000_Alert2_h32bit_16;
                }
                return(defaultSr);
            }

            if (defaultSrVisible && !defaultSr.Equals(suggestedSr))
            {
                sb.AppendFormat(Messages.NEWVMWIZARD_STORAGEPAGE_DEFAULT_NOSPACE, defaultSr.Name().Ellipsise(50)).AppendLine();
            }
            else if (defaultSrHasSpace && !defaultSr.Equals(suggestedSr))
            {
                sb.AppendFormat(Affinity == null
                        ? Messages.NEWVMWIZARD_STORAGEPAGE_DEFAULT_LOCAL_NO_HOME
                        : Messages.NEWVMWIZARD_STORAGEPAGE_DEFAULT_LOCAL,
                                defaultSr.Name().Ellipsise(50)).AppendLine();
            }

            foreach (SR sr in connection.Cache.SRs)
            {
                if (sr.SupportsVdiCreate() && !sr.IsBroken(false) && !sr.IsFull() &&
                    sr.CanBeSeenFrom(affinity) && sr.VdiCreationCanProceed(diskSize))
                {
                    if (suggestedSr != null || defaultSr != null)
                    {
                        sb.AppendLine(Messages.NEWVMWIZARD_STORAGEPAGE_XC_SELECTION);
                        tooltip = sb.ToString();
                        icon    = Images.StaticImages._000_Alert2_h32bit_16;
                    }
                    return(sr);
                }
            }

            return(null);
        }
Exemple #18
0
        private Problem GetProblem(IXenConnection connection, XenRef <VM> vmRef, string[] exception)
        {
            try
            {
                System.Diagnostics.Trace.Assert(exception.Length > 0);

                var vm = connection.Resolve <VM>(vmRef);

                if (vm == null)
                {
                    throw new NullReferenceException(exception[0]);
                }

                switch (exception[0])
                {
                case Failure.VM_REQUIRES_SR:
                    XenRef <SR> srRef = new XenRef <SR>(exception[2]);
                    SR          sr    = connection.Resolve <SR>(srRef);

                    if (sr == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_SR);
                    }

                    if (sr.content_type == SR.Content_Type_ISO)
                    {
                        return(new LocalCD(this, vm));
                    }
                    else if (!sr.shared)
                    {
                        // Only show the problem if it is really local storage
                        // As the pbd-plug checks will pick up broken storage.
                        return(new LocalStorage(this, vm));
                    }

                    return(null);

                case Failure.VM_MISSING_PV_DRIVERS:
                    return(new NoPVDrivers(this, vm));

                case Failure.VM_LACKS_FEATURE:
                    return(new CannotMigrateVM(this, vm, GetMoreSpecificReasonForCannotMigrateVm(vm, CannotMigrateVM.CannotMigrateVMReason.CannotMigrateVm)));

                case Failure.VM_LACKS_FEATURE_SUSPEND:
                    return(new CannotMigrateVM(this, vm, GetMoreSpecificReasonForCannotMigrateVm(vm, CannotMigrateVM.CannotMigrateVMReason.LacksFeatureSuspend)));

                case Failure.VM_HAS_PCI_ATTACHED:
                    return(new CannotMigrateVM(this, vm, GetMoreSpecificReasonForCannotMigrateVm(vm, CannotMigrateVM.CannotMigrateVMReason.HasPCIAttached)));

                case "VM_OLD_PV_DRIVERS":
                    return(new PVDriversOutOfDate(this, vm));

                case Failure.NO_HOSTS_AVAILABLE:
                    //CA-63531: Boston server will come here in case of single host pool or standalone host
                    return(new NoHosts(this, vm));

                case Failure.HOST_NOT_ENOUGH_FREE_MEMORY:
                    Pool pool = Helpers.GetPool(vm.Connection);

                    if (pool == null || pool.Connection.Cache.HostCount == 1)
                    {
                        //CA-63531: Cowley server will come here in case of single host pool or standalone host
                        return(new NoHosts(this, vm));
                    }

                    Host host = vm.Connection.Resolve(vm.resident_on);
                    return(new NotEnoughMem(this, host));

                case Failure.VM_REQUIRES_NETWORK:
                    XenRef <XenAPI.Network> netRef  = new XenRef <XenAPI.Network>(exception[2]);
                    XenAPI.Network          network = connection.Resolve(netRef);

                    if (network == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK);
                    }

                    return(new VMCannotSeeNetwork(this, vm, network));

                case Failure.VM_REQUIRES_GPU:
                    return(new CannotMigrateVM(this, vm, CannotMigrateVM.CannotMigrateVMReason.CannotMigrateVmNoGpu));

                case Failure.VM_HAS_VGPU:
                    return(new VmHasVgpu(this, vm));

                case Failure.OTHER_OPERATION_IN_PROGRESS:
                    return(new CannotMigrateVM(this, vm, CannotMigrateVM.CannotMigrateVMReason.OperationInProgress));

                default:
                    throw new NullReferenceException(exception[0]);
                }
            }
            catch (Exception e)
            {
                log.Debug("Exception parsing exception", e);

                throw new Failure(new List <String>(exception));
            }
        }
Exemple #19
0
        /// <summary>
        /// returns null if nothing suitable
        /// </summary>
        private static SR GetBeskDiskStorage(IXenConnection connection, long diskSize, Host affinity, SR suggestion)
        {
            // try suggestion
            if (suggestion != null && suggestion.FreeSpace > diskSize && suggestion.CanBeSeenFrom(affinity))
                return suggestion;

            // try default sr
            SR def_sr = connection.Resolve(Helpers.GetPoolOfOne(connection).default_SR);
            if (def_sr != null && def_sr.FreeSpace > diskSize && def_sr.CanBeSeenFrom(affinity))
                return def_sr;

            // pick an sr
            foreach (SR sr in connection.Cache.SRs)
            {
                if (!sr.CanCreateVmOn())
                    continue;

                if (sr.FreeSpace > diskSize && sr.CanBeSeenFrom(affinity))
                    return sr;
            }

            // there is nothing
            return null;
        }
Exemple #20
0
        private Problem GetProblem(IXenConnection connection, XenRef <VM> vmRef, string[] exception)
        {
            try
            {
                System.Diagnostics.Trace.Assert(exception.Length > 0);

                VM vm;

                switch (exception[0])
                {
                case Failure.VM_REQUIRES_SR:
                    vm = connection.Resolve <VM>(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_SR);
                    }

                    XenRef <SR> srRef = new XenRef <SR>(exception[2]);
                    SR          sr    = connection.Resolve <SR>(srRef);

                    if (sr == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_SR);
                    }

                    if (sr.content_type == SR.Content_Type_ISO)
                    {
                        return(new LocalCD(this, vm));
                    }
                    else if (!sr.shared)
                    {
                        // Only show the problem if it is really local storage
                        // As the pbd-plug checks will pick up broken storage.
                        return(new LocalStorage(this, vm));
                    }

                    return(null);

                case Failure.VM_MISSING_PV_DRIVERS:
                    vm = connection.Resolve <VM>(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.VM_MISSING_PV_DRIVERS);
                    }

                    return(new NoPVDrivers(this, vm));

                case "VM_OLD_PV_DRIVERS":
                    vm = connection.Resolve <VM>(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException("VM_OLD_PV_DRIVERS");
                    }

                    return(new PVDriversOutOfDate(this, vm));

                case Failure.NO_HOSTS_AVAILABLE:
                    //CA-63531: Boston server will come here in case of single host pool or standalone host
                    vm = connection.Resolve <VM>(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.NO_HOSTS_AVAILABLE);
                    }

                    return(new NoHosts(this, vm));

                case Failure.HOST_NOT_ENOUGH_FREE_MEMORY:
                    vm = connection.Resolve <VM>(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.HOST_NOT_ENOUGH_FREE_MEMORY);
                    }

                    Pool pool = Helpers.GetPool(vm.Connection);

                    if (pool == null || pool.Connection.Cache.HostCount == 1)
                    {
                        //CA-63531: Cowley server will come here in case of single host pool or standalone host
                        return(new NoHosts(this, vm));
                    }

                    Host host = vm.Connection.Resolve(vm.resident_on);
                    return(new NotEnoughMem(this, host));

                case Failure.VM_REQUIRES_NETWORK:
                    vm = connection.Resolve(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK);
                    }

                    XenRef <XenAPI.Network> netRef  = new XenRef <XenAPI.Network>(exception[2]);
                    XenAPI.Network          network = connection.Resolve(netRef);

                    if (network == null)
                    {
                        throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK);
                    }

                    return(new VMCannotSeeNetwork(this, vm, network));

                case Failure.VM_HAS_VGPU:
                    vm = connection.Resolve(vmRef);

                    if (vm == null)
                    {
                        throw new NullReferenceException(Failure.VM_HAS_VGPU);
                    }

                    return(new VmHasVgpu(this, vm));

                default:
                    throw new NullReferenceException(exception[0]);
                }
            }
            catch (Exception e)
            {
                log.Debug("Exception parsing exception", e);
                log.Debug(e, e);

                throw new Failure(new List <String>(exception));
            }
        }
Exemple #21
0
        public static bool HasIpForClusterNetwork(IXenConnection masterConnection, Host slaveHost, out bool clusterHostInBond)
        {
            clusterHostInBond = false;
            var clusterHost = masterConnection.Cache.Cluster_hosts.FirstOrDefault();

            if (clusterHost == null)
            {
                return(true);
            }

            var clusterHostPif = clusterHost.Connection.Resolve(clusterHost.PIF);

            if (clusterHostPif == null)
            {
                return(true);
            }

            // if this PIF is a VLAN, then use the tagged_PIF field of the VLAN
            if (clusterHostPif.VLAN >= 0)
            {
                var vlan = masterConnection.Resolve(clusterHostPif.VLAN_master_of);

                if (vlan != null)
                {
                    var taggedPif = masterConnection.Resolve(vlan.tagged_PIF);
                    if (taggedPif != null)
                    {
                        clusterHostPif = taggedPif;
                    }
                }
            }

            clusterHostInBond = clusterHostPif.IsBondNIC();

            var pifsWithIPAddress = 0;

            List <string> ids = new List <string>();

            if (clusterHostInBond)
            {
                List <PIF> slaves = new List <PIF>();

                var bonds = masterConnection.ResolveAll(clusterHostPif.bond_master_of);

                foreach (var bond in bonds)
                {
                    slaves.AddRange(masterConnection.ResolveAll(bond.slaves));
                }

                ids.AddRange(slaves.Select(slave => slave.device));
            }
            else
            {
                ids.Add(clusterHostPif.device);
            }

            var pifs = slaveHost.Connection.ResolveAll(slaveHost.PIFs);

            foreach (var pif in pifs)
            {
                if (pif.IsManagementInterface(false) && ids.Contains(pif.device))
                {
                    pifsWithIPAddress += 1;
                }
            }

            return(pifsWithIPAddress == 1);
        }
Exemple #22
0
        public static void CheckPlugPBDsForVMs(IXenConnection connection, List <XenRef <VM> > vmRefs, bool ignoreFailure = false)
        {
            var pbds = new List <PBD>();

            foreach (XenRef <VM> vmRef in vmRefs)
            {
                VM vm = connection.TryResolveWithTimeout(vmRef);

                foreach (var vbdRef in vm.VBDs)
                {
                    var vbd = connection.Resolve(vbdRef);
                    if (vbd == null)
                    {
                        continue;
                    }

                    VDI vdi = connection.Resolve(vbd.VDI);
                    if (vdi == null)
                    {
                        continue;
                    }

                    SR sr = connection.Resolve(vdi.SR);
                    if (sr == null)
                    {
                        continue;
                    }

                    foreach (var pbdRef in sr.PBDs)
                    {
                        var pbd = connection.Resolve(pbdRef);
                        if (pbd != null && !pbds.Contains(pbd))
                        {
                            pbds.Add(pbd);
                        }
                    }
                }
            }

            foreach (PBD pbd in pbds)
            {
                Session session = pbd.Connection.DuplicateSession();

                log.DebugFormat("Waiting for PBDs {0} to become plugged", pbd.Name());
                // Wait 2 min for PBD to become plugged
                if (WaitForPlug(session, pbd.opaque_ref))
                {
                    continue;
                }

                // if it's still unplugged, try plugging it - this will probably
                // fail, but at least we'll get a better error message.
                try
                {
                    log.DebugFormat("Plugging PBD {0}", pbd.Name());
                    plug(session, pbd.opaque_ref);
                }
                catch (Exception e)
                {
                    log.Debug(string.Format("Error plugging PBD {0}", pbd.Name()), e);

                    if (!ignoreFailure)
                    {
                        throw;
                    }
                }
            }
        }
        private Problem GetProblem(IXenConnection connection, XenRef<VM> vmRef, string[] exception)
        {
            try
            {
                System.Diagnostics.Trace.Assert(exception.Length > 0);

                VM vm;

                switch (exception[0])
                {
                    case Failure.VM_REQUIRES_SR:
                        vm = connection.Resolve<VM>(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.VM_REQUIRES_SR);

                        XenRef<SR> srRef = new XenRef<SR>(exception[2]);
                        SR sr = connection.Resolve<SR>(srRef);

                        if (sr == null)
                            throw new NullReferenceException(Failure.VM_REQUIRES_SR);

                        if (sr.content_type == SR.Content_Type_ISO)
                        {
                            return new LocalCD(this, vm);
                        }
                        else if (!sr.shared)
                        {
                            // Only show the problem if it is really local storage
                            // As the pbd-plug checks will pick up broken storage.
                            return new LocalStorage(this, vm);
                        }

                        return null;

                    case Failure.VM_MISSING_PV_DRIVERS:
                        vm = connection.Resolve<VM>(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.VM_MISSING_PV_DRIVERS);

                        return new NoPVDrivers(this, vm);

                    case "VM_OLD_PV_DRIVERS":
                        vm = connection.Resolve<VM>(vmRef);

                        if (vm == null)
                            throw new NullReferenceException("VM_OLD_PV_DRIVERS");

                        return new PVDriversOutOfDate(this, vm);

                    case Failure.NO_HOSTS_AVAILABLE:
                        //CA-63531: Boston server will come here in case of single host pool or standalone host
                        vm = connection.Resolve<VM>(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.NO_HOSTS_AVAILABLE);

                        return new NoHosts(this, vm);

                    case Failure.HOST_NOT_ENOUGH_FREE_MEMORY:
                        vm = connection.Resolve<VM>(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.HOST_NOT_ENOUGH_FREE_MEMORY);

                        Pool pool = Helpers.GetPool(vm.Connection);

                        if (pool == null || pool.Connection.Cache.HostCount == 1)
                        {
                            //CA-63531: Cowley server will come here in case of single host pool or standalone host
                            return new NoHosts(this, vm);
                        }

                        Host host = vm.Connection.Resolve(vm.resident_on);
                        return new NotEnoughMem(this, host);

                    case Failure.VM_REQUIRES_NETWORK:
                        vm = connection.Resolve(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK);

                        XenRef<XenAPI.Network> netRef = new XenRef<XenAPI.Network>(exception[2]);
                        XenAPI.Network network = connection.Resolve(netRef);

                        if (network == null)
                            throw new NullReferenceException(Failure.VM_REQUIRES_NETWORK);

                        return new VMCannotSeeNetwork(this, vm, network);

                    case Failure.VM_HAS_VGPU:
                        vm = connection.Resolve(vmRef);

                        if (vm == null)
                            throw new NullReferenceException(Failure.VM_HAS_VGPU);

                        return new VmHasVgpu(this, vm);

                    default:
                        throw new NullReferenceException(exception[0]);
                }
            }
            catch (Exception e)
            {
                log.Debug("Exception parsing exception", e);
                log.Debug(e, e);

                throw new Failure(new List<String>(exception));
            }
        }
Exemple #24
0
        /// <summary>
        /// Tries to find the best SR for the given VDI considering the suggestedSR which has priority over other SRs in this check.
        /// SuggestedSR, default SR, other SRs are checked.
        /// Returns first suitable SR or NULL.
        /// </summary>
        private static SR GetBeskDiskStorage(IXenConnection connection, VDI disk, Host affinity, SR suggestedSR)
        {
            // try suggestion
            if (suggestedSR != null && suggestedSR.CanBeSeenFrom(affinity) && IsSufficientFreeSpaceAvailableOnSrForVdi(suggestedSR, disk))
                return suggestedSR;

            // try default sr
            SR defaultSR = connection.Resolve(Helpers.GetPoolOfOne(connection).default_SR);
            if (defaultSR != null && defaultSR.CanBeSeenFrom(affinity) && IsSufficientFreeSpaceAvailableOnSrForVdi(defaultSR, disk))
                return defaultSR;

            // pick an sr
            foreach (SR sr in connection.Cache.SRs)
            {
                if (!sr.CanCreateVmOn())
                    continue;

                if (sr.CanBeSeenFrom(affinity) && IsSufficientFreeSpaceAvailableOnSrForVdi(sr, disk))
                    return sr;
            }

            // there has been no suitable SR found
            return null;
        }
        /// <summary>
        /// Checks if all VMs are still available for migration and shows a warning message if the check fails
        /// </summary>
        /// <returns>true if check succeded, false if failed</returns>
        internal static bool AllVMsAvailable(Dictionary<string, VmMapping> vmMappings, IXenConnection connection)
        {
            Func<bool> vmCheck = delegate
            {
                if (vmMappings == null || vmMappings.Count == 0 || connection == null)
                    return false;
                return vmMappings.All(kvp => connection.Resolve(new XenRef<VM>(kvp.Key)) != null);
            };

            return PerformCheck(vmCheck);
        }
 public VdiOpenDatabaseAction(IXenConnection connection, VDI vdi)
     : base(connection, String.Format(Messages.ACTION_VDI_OPEN_DATABASE_TITLE, connection.Resolve(vdi.SR).Name))
 {
     _vdi = vdi;
     #region RBAC Dependencies
     ApiMethodsToRoleCheck.Add("VDI.open_database");
     ApiMethodsToRoleCheck.Add("Session.get_record");
     #endregion
 }
Exemple #27
0
        public DiskGridRowItem(IXenConnection connection, VDI vdi, VBD vbd, bool isNew, Host affinity)
        {
            SourceDisk = vdi;
            Disk = new VDI();
            Device = new VBD();
            Connection = connection;

            Disk.virtual_size = vdi.virtual_size;
            SR sr = GetBeskDiskStorage(Connection, Disk.virtual_size, affinity, Connection.Resolve(vdi.SR));
            Disk.SR = new XenRef<SR>(sr != null ? sr.opaque_ref : Helper.NullOpaqueRef);
            Disk.type = vdi.type;
            Device.userdevice = vbd.userdevice;
            Device.bootable = vbd.bootable;

            Disk.name_label = vdi.name_label;
            Disk.read_only = vdi.read_only;
            Disk.name_description = vdi.name_description;
            Device.mode = vbd.mode;

            CanDelete = Disk.type == vdi_type.user && isNew;
            CanResize = isNew;
            MinSize = 0;

            AddCells();
        }
        public NewDiskDialog(IXenConnection connection, VM vm, SrPicker.SRPickerType PickerUsage, VDI diskTemplate, Host affinity, bool canResize, long minSize, IEnumerable<VDI> vdiNamesInUse)
            : this(connection, vdiNamesInUse)
        {
            TheVM = vm;
            DiskTemplate = diskTemplate;
            CanResize = canResize;
            MinSize = minSize;
            this.PickerUsage = PickerUsage;
            SrListBox.SetAffinity(affinity);

            Pool pool_sr = Helpers.GetPoolOfOne(connection);
            if (pool_sr != null)
            {
                SrListBox.DefaultSR = connection.Resolve(pool_sr.default_SR); //if default sr resolves to null the first sr in the list will be selected
            }
            SrListBox.selectDefaultSROrAny();

            LoadValues();
        }
        public VdiLoadMetadataAction(IXenConnection connection, VDI vdi)
            : base(connection, String.Format(Messages.ACTION_VDI_LOAD_METADATA_TITLE, connection.Resolve(vdi.SR).Name))
        {
            _poolMetadata = new PoolMetadata(null, vdi);

            Pool = Helpers.GetPoolOfOne(connection);

            #region RBAC Dependencies
            ApiMethodsToRoleCheck.Add("VDI.open_database");
            ApiMethodsToRoleCheck.Add("Session.get_record");
            ApiMethodsToRoleCheck.Add("Pool.get_all_records");
            ApiMethodsToRoleCheck.Add("VM_appliance.get_all_records");
            ApiMethodsToRoleCheck.Add("VM.get_all_records");
            #endregion
        }
Exemple #30
0
        private void PopulateInterfaces(Pool pool, Host host, IXenConnection connection)
        {
            Dictionary<XenAPI.Network, bool> networksAdded = new Dictionary<XenAPI.Network, bool>();

            comboInterfaces.Items.Clear();

            foreach (PIF pif in connection.Cache.PIFs)
            {
                // If the current selection is for a host, rather than a pool, only show
                // management interfaces with PIFs on that host.
                if (pool == null && host != null && pif.host.opaque_ref != host.opaque_ref)
                    continue;

                if (pif.IsManagementInterface(XenAdmin.Properties.Settings.Default.ShowHiddenVMs))
                {
                    XenAPI.Network network = connection.Resolve(pif.network);
                    if (network != null &&  // this should have been checked already by pif.IsManagementInterface, but...
                        !networksAdded.ContainsKey(network))
                    {
                        comboInterfaces.Items.Add(network);
                        networksAdded[network] = true;
                    }
                }
            }
            comboInterfaces.SelectedIndexChanged += new EventHandler(comboInterfaces_SelectedIndexChanged);

            if (comboInterfaces.Items.Count > 0)
                comboInterfaces.SelectedIndex = 0;
        }
        private void EnableAppropriateHostsNoWlb(Session session)
        {
            SelectedItemCollection selection  = Command.GetSelection();
            IXenConnection         connection = selection[0].Connection;

            VMOperationCommand cmdHome = new VMOperationHomeServerCommand(Command.MainWindowCommandInterface, selection, _operation, session);
            Host affinityHost          = connection.Resolve(((VM)Command.GetSelection()[0].XenObject).affinity);

            Program.Invoke(Program.MainWindow, delegate
            {
                var firstItem = (VMOperationToolStripMenuSubItem)base.DropDownItems[0];

                bool oldMigrateToHomeCmdCanRun = cmdHome.CanExecute();
                if (affinityHost == null || _operation == vm_operations.start_on || oldMigrateToHomeCmdCanRun)
                {
                    firstItem.Command = cmdHome;
                    firstItem.Enabled = oldMigrateToHomeCmdCanRun;
                }
                else
                {
                    VMOperationCommand cpmCmdHome = new CrossPoolMigrateToHomeCommand(Command.MainWindowCommandInterface, selection, affinityHost);

                    if (cpmCmdHome.CanExecute())
                    {
                        firstItem.Command = cpmCmdHome;
                        firstItem.Enabled = true;
                    }
                    else
                    {
                        firstItem.Command = cmdHome;
                        firstItem.Enabled = false;
                    }
                }
            });

            List <VMOperationToolStripMenuSubItem> dropDownItems = DropDownItems.Cast <VMOperationToolStripMenuSubItem>().ToList();

            // Adds the migrate wizard button, do this before the enable checks on the other items
            Program.Invoke(Program.MainWindow, () => AddAdditionalMenuItems(selection));

            foreach (VMOperationToolStripMenuSubItem item in dropDownItems)
            {
                if (_isDropDownClosed)
                {
                    // Stop making requests to assert can start on each host after dropdown is closed
                    break;
                }

                Host host = item.Tag as Host;
                if (host != null)
                {
                    // API calls could happen in CanExecute(), which take time to wait.
                    // So a Producer-Consumer-Queue with size 25 is used here to :
                    //   1. Make API calls for different menu items happen in parallel;
                    //   2. Limit the count of concurrent threads (now it's 25).
                    workerQueueWithouWlb.EnqueueItem(() =>
                    {
                        if (_isDropDownClosed)
                        {
                            return;
                        }
                        VMOperationCommand cmd         = new VMOperationHostCommand(Command.MainWindowCommandInterface, selection, delegate { return(host); }, host.Name().EscapeAmpersands(), _operation, session);
                        CrossPoolMigrateCommand cpmCmd = new CrossPoolMigrateCommand(Command.MainWindowCommandInterface, selection, host, _resumeAfter);

                        VMOperationToolStripMenuSubItem tempItem = item;
                        bool oldMigrateCmdCanRun = cmd.CanExecute();
                        if ((_operation == vm_operations.start_on) || oldMigrateCmdCanRun)
                        {
                            Program.Invoke(Program.MainWindow, delegate
                            {
                                tempItem.Command = cmd;
                                tempItem.Enabled = oldMigrateCmdCanRun;
                            });
                        }
                        else
                        {
                            bool crossPoolMigrateCmdCanRun = cpmCmd.CanExecute();
                            if (crossPoolMigrateCmdCanRun || !string.IsNullOrEmpty(cpmCmd.CantExecuteReason))
                            {
                                Program.Invoke(Program.MainWindow, delegate
                                {
                                    tempItem.Command = cpmCmd;
                                    tempItem.Enabled = crossPoolMigrateCmdCanRun;
                                });
                            }
                            else
                            {
                                Program.Invoke(Program.MainWindow, delegate
                                {
                                    tempItem.Command = cmd;
                                    tempItem.Enabled = oldMigrateCmdCanRun;
                                });
                            }
                        }
                    });
                }
            }
        }
Exemple #32
0
        private static void CheckAndPlugPBDsFor(IXenConnection connection, List<XenRef<VM>> vmRefs, PlugMode plugMode)
        {
            //Program.AssertOffEventThread();

            List<VM> vms = new List<VM>();

            foreach (XenRef<VM> vmRef in vmRefs)
            {
                VM vm = null;
                while ((vm = connection.Resolve<VM>(vmRef)) == null)
                    Thread.Sleep(100);

                vms.Add(vm);
            }

            CheckAndPlugPBDsFor(vms, plugMode);
        }