private void InstallSuppPack(Host host, VDI vdi)
        {
            // Set the correct connection object, for RecomputeCanCancel
            Connection = host.Connection;
            Session session = host.Connection.DuplicateSession();

            try
            {
                Description = String.Format(Messages.APPLYING_PATCH, vdi.Name(), host.Name());
                Host.call_plugin(session, host.opaque_ref, "install-supp-pack", "install", new Dictionary <string, string> {
                    { "vdi", vdi.uuid }
                });
                Description = String.Format(Messages.PATCH_APPLIED, vdi.Name(), host.Name());
            }
            catch (Failure failure)
            {
                log.ErrorFormat("Plugin call install-supp-pack.install({0}) on {1} failed with {2}", vdi.uuid, host.Name(), failure.Message);
                log.ErrorFormat("Supplemental pack installation error description: {0}", string.Join(";", failure.ErrorDescription));
                throw new SupplementalPackInstallFailedException(string.Format(Messages.SUPP_PACK_INSTALL_FAILED, vdi.Name(), host.Name()), failure);
            }
            finally
            {
                Connection = null;
            }
        }
Exemple #2
0
 private void Update()
 {
     if (TheVDI.type == vdi_type.crashdump || TheVDI.type == vdi_type.ephemeral || TheVDI.type == vdi_type.suspend)
     {
         Show = false;
     }
     else if ((TheVDI.VBDs.Count > 0 && !TheVDI.sharable))
     {
         bool allRO = true;
         foreach (VBD vbd in TheVDI.Connection.ResolveAll <VBD>(TheVDI.VBDs))
         {
             if (!vbd.IsReadOnly() && vbd.currently_attached)
             {
                 allRO = false;
                 break;
             }
         }
         Show = allRO;
         if (Show)
         {
             ForceReadOnly = true;
             Text          = String.IsNullOrEmpty(TheVDI.Name()) ? Messages.NO_NAME : TheVDI.Name();
             if (!string.IsNullOrEmpty(TheVDI.Description()))
             {
                 Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description(), Util.DiskSizeString(TheVDI.virtual_size));
             }
             else
             {
                 Description = Util.DiskSizeString(TheVDI.virtual_size);
             }
             Image = Images.GetImage16For(Icons.VDI);
         }
     }
     else
     {
         Show          = true;
         ForceReadOnly = TheVDI.read_only;
         Text          = String.IsNullOrEmpty(TheVDI.Name()) ? Messages.NO_NAME : TheVDI.Name();
         if (!string.IsNullOrEmpty(TheVDI.Description()))
         {
             Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description(), Util.DiskSizeString(TheVDI.virtual_size));
         }
         else
         {
             Description = Util.DiskSizeString(TheVDI.virtual_size);
         }
         Image = Images.GetImage16For(Icons.VDI);
     }
 }
Exemple #3
0
        private void AddStorageMappings(ref List <SummaryDetails> decoratedSummary)
        {
            bool firstItem = true;

            foreach (var pair in mapping.Storage)
            {
                VDI vdi = connection.Resolve(new XenRef <VDI>(pair.Key));
                if (vdi == null || vdi.is_a_snapshot) // don't display the storage mappings for the shapshots
                {
                    continue;
                }

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

                if (firstItem)
                {
                    decoratedSummary.Add(new SummaryDetails(Messages.CPM_SUMMARY_KEY_STORAGE, valueToAdd));
                    firstItem = false;
                }
                else
                {
                    decoratedSummary.Add(new SummaryDetails(String.Empty, valueToAdd));
                }
            }
        }
Exemple #4
0
        public NewDiskDialog(IXenConnection connection, VM vm, Host affinity,
                             SrPicker.SRPickerType pickerUsage = SrPicker.SRPickerType.VM, VDI diskTemplate = null,
                             bool canResize = true, long minSize = 0, IEnumerable <VDI> vdiNamesInUse = null)
            : base(connection ?? throw new ArgumentNullException(nameof(connection)))
        {
            InitializeComponent();

            TheVM                  = vm;
            _VDINamesInUse         = vdiNamesInUse ?? new List <VDI>();
            diskSpinner1.CanResize = canResize;

            if (diskTemplate == null)
            {
                NameTextBox.Text = GetDefaultVDIName();
                diskSpinner1.Populate(minSize: minSize);
                UpdateErrorsAndButtons();
                SrListBox.PopulateAsync(pickerUsage, connection, affinity, null, null);
            }
            else
            {
                DiskTemplate            = diskTemplate;
                NameTextBox.Text        = DiskTemplate.Name();
                DescriptionTextBox.Text = DiskTemplate.Description();
                Text          = Messages.EDIT_DISK;
                OkButton.Text = Messages.OK;
                diskSpinner1.Populate(DiskTemplate.virtual_size, minSize);
                UpdateErrorsAndButtons();
                SrListBox.PopulateAsync(pickerUsage, connection, affinity, connection.Resolve(DiskTemplate.SR), null);
            }
        }
Exemple #5
0
        private void LoadValues()
        {
            if (DiskTemplate == null)
            {
                return;
            }

            NameTextBox.Text        = DiskTemplate.Name();
            DescriptionTextBox.Text = DiskTemplate.Description();
            SrListBox.selectSRorDefaultorAny(connection.Resolve(DiskTemplate.SR));

            // select the appropriate unit, based on size (CA-45905)
            currentSelectedUnits = DiskTemplate.virtual_size >= Util.BINARY_GIGA ? DiskSizeUnits.GB : DiskSizeUnits.MB;
            SelectedUnits        = currentSelectedUnits;
            SetNumUpDownIncrementAndDecimals(DiskSizeNumericUpDown, SelectedUnits.ToString());
            decimal newValue = (decimal)Math.Round((double)DiskTemplate.virtual_size / GetUnits(), DiskSizeNumericUpDown.DecimalPlaces);

            DiskSizeNumericUpDown.Value = newValue >= DiskSizeNumericUpDown.Minimum && newValue <= DiskSizeNumericUpDown.Maximum ?
                                          newValue : DiskSizeNumericUpDown.Maximum;

            if (MinSize > 0)
            {
                min = (decimal)((double)MinSize / GetUnits());
            }
            DiskSizeNumericUpDown.Enabled = CanResize;

            Text          = Messages.EDIT_DISK;
            OkButton.Text = Messages.OK;
        }
        protected override void RunWithSession(ref Session session)
        {
            AddProgressStep(string.Format(Messages.UPDATES_WIZARD_APPLYING_UPDATE, vdi.Name(), host.Name()));
            var suppPackVdis = new Dictionary <Host, VDI> {
                { host, vdi }
            };

            new InstallSupplementalPackAction(suppPackVdis, true).RunExternal(session);
        }
Exemple #7
0
        public CreateDiskAction(IXenObject obj) : base(obj)
        {
            VDI disk = obj as VDI;

            if (disk != null)
            {
                Title = string.Format(Messages.ACTION_VDI_CREATING_TITLE, disk.Name(),
                                      disk.Connection.Resolve <SR>(disk.SR).NameWithoutHost());
            }
            Description = Messages.ACTION_VDI_CREATING;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="vm"></param>
        /// <param name="vdi">May be null, indicating that the CD should be ejected (i.e. set to empty).</param>
        /// <param name="cdrom">Must not be null.</param>
        public ChangeVMISOAction(IXenConnection connection, VM vm,
                                 VDI vdi, VBD cdrom)
            : base(connection, vdi == null ? String.Format(Messages.ISO_UNLOADING, vm.Name()) :
                   String.Format(Messages.ISO_LOADING, vdi.Name(), vm.Name()))
        {
            this.VM    = vm;
            this.vdi   = vdi;
            this.cdrom = cdrom;

            System.Diagnostics.Trace.Assert(this.cdrom != null, "ChangeVMISOAction ctor: cdrom vbd must not be null");
            System.Diagnostics.Trace.Assert(this.VM != null, "ChangeVMISOAction ctor: VM must not be null");
        }
Exemple #9
0
        private void OkBtn_Click(object sender, EventArgs e)
        {
            DiskListVdiItem item = DiskListTreeView.SelectedItem as DiskListVdiItem;

            if (item == null)
            {
                return;
            }

            VDI TheVDI = item.TheVDI;

            // Run this stuff off the event thread, since it involves a server call
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                // Get a spare userdevice
                string[] uds = VM.get_allowed_VBD_devices(connection.DuplicateSession(), TheVM.opaque_ref);
                if (uds.Length == 0)
                {
                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        using (var dlg = new ErrorDialog(FriendlyErrorNames.VBDS_MAX_ALLOWED)
                        {
                            WindowTitle = Messages.DISK_ATTACH
                        })
                        {
                            dlg.ShowDialog(Program.MainWindow);
                        }
                    });

                    return;
                }
                string ud = uds[0];

                VBD vbd      = new VBD();
                vbd.VDI      = new XenRef <VDI>(TheVDI);
                vbd.VM       = new XenRef <VM>(TheVM);
                vbd.bootable = ud == "0";
                vbd.device   = "";
                vbd.SetIsOwner(TheVDI.VBDs.Count == 0);
                vbd.empty       = false;
                vbd.userdevice  = ud;
                vbd.type        = vbd_type.Disk;
                vbd.mode        = ReadOnlyCheckBox.Checked ? vbd_mode.RO : vbd_mode.RW;
                vbd.unpluggable = true;

                // Try to hot plug the VBD.
                var action = new VbdSaveAndPlugAction(TheVM, vbd, TheVDI.Name(), null, false);
                action.ShowUserInstruction += Action_ShowUserInstruction;
                action.RunAsync();
            });

            Close();
        }
Exemple #10
0
        private AsyncAction getActivateVBDAction(VBD vbd)
        {
            VDI    vdi       = vbd.Connection.Resolve <VDI>(vbd.VDI);
            VM     vm        = vbd.Connection.Resolve <VM>(vbd.VM);
            String title     = String.Format(Messages.ACTION_DISK_ACTIVATING_TITLE, vdi.Name(), vm.Name());
            String startDesc = Messages.ACTION_DISK_ACTIVATING;
            String endDesc   = Messages.ACTION_DISK_ACTIVATED;

            AsyncAction action = new DelegatedAsyncAction(vbd.Connection,
                                                          title, startDesc, endDesc, session => VBD.plug(session, vbd.opaque_ref), "vbd.plug");

            action.VM = vm;
            return(action);
        }
Exemple #11
0
        protected override void Run()
        {
            try
            {
                Title       = Description = string.Format(Messages.ACTION_MOVING_VDI_STATUS, Helpers.GetName(vdi));
                RelatedTask = VDI.async_pool_migrate(Session, vdi.opaque_ref, SR.opaque_ref, new Dictionary <string, string>());
                PollToCompletion();
            }
            catch (CancelledException)
            {
                Description = string.Format(Messages.ACTION_VM_MIGRATE_CANCELLED, vdi.Name());
                throw;
            }
            catch (Failure boo)
            {
                Description = boo.Message;
                throw;
            }

            Description = Messages.ACTION_VM_MIGRATED;
        }
Exemple #12
0
        public NewDiskDialog(IXenConnection connection, VM vm, Host affinity,
                             SrPicker.SRPickerType pickerUsage = SrPicker.SRPickerType.VM, VDI diskTemplate = null,
                             bool canResize = true, long minSize = 0, IEnumerable <VDI> vdiNamesInUse = null)
            : base(connection ?? throw new ArgumentNullException(nameof(connection)))
        {
            InitializeComponent();

            TheVM          = vm;
            _VDINamesInUse = vdiNamesInUse ?? new List <VDI>();

            SrListBox.Connection = connection;
            SrListBox.Usage      = 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
            }

            if (diskTemplate == null)
            {
                NameTextBox.Text = GetDefaultVDIName();
                SrListBox.selectDefaultSROrAny();
                diskSpinner1.Populate(minSize: minSize);
            }
            else
            {
                DiskTemplate            = diskTemplate;
                NameTextBox.Text        = DiskTemplate.Name();
                DescriptionTextBox.Text = DiskTemplate.Description();
                SrListBox.selectSRorDefaultorAny(connection.Resolve(DiskTemplate.SR));
                Text          = Messages.EDIT_DISK;
                OkButton.Text = Messages.OK;
                diskSpinner1.Populate(DiskTemplate.virtual_size, minSize);
            }

            diskSpinner1.CanResize = canResize;
        }
Exemple #13
0
        private object CellValue(int col)
        {
            switch (col)
            {
            case 0:
                return(VBD.userdevice);

            case 1:
                return(VDI.Name());

            case 2:
                return(VDI.Description());

            case 3:
                return(SR.Name());

            case 4:
                string name;
                return(VDI.sm_config.TryGetValue("displayname", out name) ? name : "");

            case 5:
                return(VDI.SizeText());

            case 6:
                return(VBD.IsReadOnly() ? Messages.YES : Messages.NO);

            case 7:
                return(GetPriorityString(VBD.GetIoNice()));

            case 8:
                return(VBD.currently_attached ? Messages.YES : Messages.NO);

            case 9:
                return(VBD.device == "" ? Messages.STORAGE_PANEL_UNKNOWN : string.Format("/dev/{0}", VBD.device));

            default:
                throw new ArgumentException(String.Format("Invalid column number {0} in VBDRenderer.CellValue()", col));
            }
        }
        protected override void Run()
        {
            bool wasEmpty = false;

            if (!cdrom.empty)
            {
                RelatedTask = VBD.async_eject(Session, cdrom.opaque_ref);
                wasEmpty    = true;
                PollToCompletion(0, 50);
            }

            if (vdi != null)
            {
                RelatedTask = VBD.async_insert(Session, cdrom.opaque_ref, vdi.opaque_ref);
                PollToCompletion(wasEmpty ? 50 : 0, 100);
                Description = String.Format(Messages.ISO_LOADED,
                                            vdi.Name(), VM.Name());
            }
            else
            {
                Description = String.Format(Messages.ISO_UNLOADED,
                                            VM.Name());
            }
        }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, sr.Name());

            String result;

            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", diskSize, sr.Name());

            VDI          vdi    = NewVDI(sr);
            XenRef <VDI> vdiRef = null;

            try
            {
                vdiRef = VDI.create(Session, vdi);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to create VDI", ex.Message);
                throw;
            }

            log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name(), sr.Name());

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            try
            {
                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var actionPercent = (int)(((totalUploaded * 100) + percent) / totalCount);
                    Tick(actionPercent, Description);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "uploadTask", hostUrl);

                result = HTTPHelper.Put(progressDelegate, GetCancelling, true, Connection, RelatedTask, ref session, suppPackFilePath, hostUrl,
                                        (HTTP_actions.put_sss)HTTP_actions.put_import_raw_vdi,
                                        session.opaque_ref, vdiRef.opaque_ref);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to import a virtual disk over HTTP.", ex.Message);

                if (vdiRef != null)
                {
                    log.DebugFormat("Removing the VDI on a best effort basis.");

                    try
                    {
                        RemoveVDI(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        //best effort
                        log.Error("Failed to remove the VDI.", removeEx);
                    }
                }

                //after having tried to remove the VDI, the original exception is thrown for the UI
                if (ex is TargetInvocationException && ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw ex;
                }
            }
            finally
            {
                Task.destroy(Session, RelatedTask);
                RelatedTask = null;
            }

            if (localStorageHost != null)
            {
                VdiRefsToCleanUp.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefsToCleanUp.Add(server, vdiRef);
                }
            }

            //introduce ISO for Ely and higher
            if (Helpers.ElyOrGreater(Connection))
            {
                try
                {
                    var poolUpdateRef = Pool_update.introduce(Connection.Session, vdiRef);
                    poolUpdate = Connection.WaitForCache(poolUpdateRef);

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                    VdiRefsToCleanUp.Clear();
                }
                catch (Failure ex)
                {
                    if (ex.ErrorDescription != null && ex.ErrorDescription.Count > 1 && string.Equals("UPDATE_ALREADY_EXISTS", ex.ErrorDescription[0], StringComparison.InvariantCultureIgnoreCase))
                    {
                        string uuidFound = ex.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, System.StringComparison.InvariantCultureIgnoreCase));

                        //clean-up the VDI we've just created
                        try
                        {
                            RemoveVDI(Session, vdiRef);

                            //remove the vdi that have just been cleaned up
                            var remaining = VdiRefsToCleanUp.Where(kvp => kvp.Value != null && kvp.Value.opaque_ref != vdiRef.opaque_ref).ToList();
                            VdiRefsToCleanUp.Clear();
                            remaining.ForEach(rem => VdiRefsToCleanUp.Add(rem.Key, rem.Value));
                        }
                        catch
                        {
                            //best effort cleanup
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Upload failed when introducing update from VDI {0} on {1}: {2}", vdi.opaque_ref, Connection, ex.Message);
                    poolUpdate = null;

                    throw;
                }
            }
            else
            {
                poolUpdate = null;
            }

            totalUploaded++;
            Description = String.Format(Messages.SUPP_PACK_UPLOADED, sr.Name());

            foreach (Host host in servers)
            {
                SrUploadedUpdates[host] = sr;
            }

            return(result);
        }
Exemple #16
0
            private VirtualTreeNode AddVDINode(VDI vdi)
            {
                String name = String.IsNullOrEmpty(vdi.Name()) ? Messages.NO_NAME : vdi.Name();

                return(AddNode(name, Images.GetIconFor(vdi), false, vdi));
            }
 public InstallSupplementalPackPlanAction(Host host, VDI vdi)
     : base(host.Connection, string.Format(Messages.UPDATES_WIZARD_APPLYING_UPDATE, vdi.Name(), host.Name()))
 {
     this.host = host;
     this.vdi  = vdi;
 }
Exemple #18
0
        private void OkButton_Click(object sender, EventArgs e)
        {
            if (SrListBox.SR == null || SelectionNull || NameTextBox.Text == "" || !connection.IsConnected)
            {
                return;
            }

            if (DontCreateVDI)
            {
                DialogResult = DialogResult.OK;
                Close();
                return;
            }
            XenAPI.SR sr = SrListBox.SR;
            if (!sr.shared && TheVM != null && TheVM.HaPriorityIsRestart())
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.NEW_SR_DIALOG_ATTACH_NON_SHARED_DISK_HA, Messages.XENCENTER),
                           ThreeButtonDialog.ButtonYes,
                           ThreeButtonDialog.ButtonNo))
                {
                    dialogResult = dlg.ShowDialog(Program.MainWindow);
                }
                if (dialogResult != DialogResult.Yes)
                {
                    return;
                }
                new HAUnprotectVMAction(TheVM).RunExternal(TheVM.Connection.Session);
            }

            VDI vdi = NewDisk();


            if (TheVM != null)
            {
                var alreadyHasBootableDisk = HasBootableDisk(TheVM);

                Actions.DelegatedAsyncAction action = new Actions.DelegatedAsyncAction(connection,
                                                                                       string.Format(Messages.ACTION_DISK_ADDING_TITLE, NameTextBox.Text, sr.NameWithoutHost()),
                                                                                       Messages.ACTION_DISK_ADDING, Messages.ACTION_DISK_ADDED,
                                                                                       delegate(XenAPI.Session session)
                {
                    // Get legitimate unused userdevice numbers
                    string[] uds = XenAPI.VM.get_allowed_VBD_devices(session, TheVM.opaque_ref);
                    if (uds.Length == 0)
                    {
                        throw new Exception(FriendlyErrorNames.VBDS_MAX_ALLOWED);
                    }
                    string ud      = uds[0];
                    string vdiref  = VDI.create(session, vdi);
                    XenAPI.VBD vbd = NewDevice();
                    vbd.VDI        = new XenAPI.XenRef <XenAPI.VDI>(vdiref);
                    vbd.VM         = new XenAPI.XenRef <XenAPI.VM>(TheVM);

                    // CA-44959: only make bootable if there aren't other bootable VBDs.
                    vbd.bootable   = ud == "0" && !alreadyHasBootableDisk;
                    vbd.userdevice = ud;

                    // Now try to plug the VBD.
                    new XenAdmin.Actions.VbdSaveAndPlugAction(TheVM, vbd, vdi.Name(), session, false, ShowMustRebootBoxCD, ShowVBDWarningBox).RunAsync();
                });
                action.VM = TheVM;
                new Dialogs.ActionProgressDialog(action, ProgressBarStyle.Blocks).ShowDialog();
                if (!action.Succeeded)
                {
                    return;
                }
            }
            else
            {
                CreateDiskAction action = new CreateDiskAction(vdi);
                new Dialogs.ActionProgressDialog(action, ProgressBarStyle.Marquee).ShowDialog();
                if (!action.Succeeded)
                {
                    return;
                }
            }
            DialogResult = DialogResult.OK;
            Close();
        }
 /// <summary>
 /// Detaches a virtual disk
 /// </summary>
 /// <param name="disk">The VDI to detach</param>
 /// <param name="vm">The VM to detach it from</param>
 /// <param name="takeVDILock">Whether it is necessary to lock the VDI (we may be part of another disk action)</param>
 public DetachVirtualDiskAction(VDI disk, VM vm, bool takeVDILock)
     : base(disk.Connection, string.Format(Messages.ACTION_DISK_DETACHING_TITLE, disk.Name(), vm.Name(), false))
 {
     this.takeVDILock = takeVDILock;
     vdi = disk;
     if (takeVDILock)
     {
         vdi.Locked = true;
     }
     VM        = vm;
     VM.Locked = true;
     foreach (VBD v in Connection.ResolveAll <VBD>(VM.VBDs))
     {
         if (v.VDI.opaque_ref == vdi.opaque_ref)
         {
             vbd        = v;
             vbd.Locked = true;
         }
     }
 }
        public DestroyDiskAction(VDI disk)
            : base(disk.Connection, string.Format(Messages.ACTION_DISK_DELETING_TITLE, disk.Name(), disk.Connection.Resolve <SR>(disk.SR).NameWithoutHost()), false)
        {
            Disk        = disk;
            Disk.Locked = true;

            #region RBAC Dependencies
            ApiMethodsToRoleCheck.Add("vbd.unplug");
            ApiMethodsToRoleCheck.Add("vbd.destroy");
            ApiMethodsToRoleCheck.Add("vdi.destroy");
            #endregion

            SR = Connection.Resolve(Disk.SR);

            // If there is only one VM involved here we can filter it under the VM
            // Otherwise just filter under the SR
            VM relevantVM = null;
            foreach (VBD vbd in SR.Connection.ResolveAll(Disk.VBDs))
            {
                VM vm = SR.Connection.Resolve <VM>(vbd.VM);
                if (vm == null)
                {
                    continue;
                }
                if (relevantVM == null)
                {
                    relevantVM = vm;
                }
                else
                {
                    // more than one relevant VM, just give it the SR as an owner
                    relevantVM = null;
                    break;
                }
            }
            if (relevantVM != null)
            {
                VM = relevantVM;
            }
        }
        public ConfirmVMDeleteDialog(IEnumerable <VM> vms)
        {
            Util.ThrowIfParameterNull(vms, "vms");

            InitializeComponent();
            HelpButton = true;

            // We have to set the header text again here because they're in base64
            // encoding in the resx, so can't be easily localised: see CA-43371.
            listView.Groups["listViewGroupAttachedDisks"].Header = Messages.ATTACHED_VIRTUAL_DISKS;
            listView.Groups["listViewGroupSnapshots"].Header     = Messages.SNAPSHOTS;

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

            if (vmList.Count == 1)
            {
                String type = vmList[0].is_a_template ? Messages.TEMPLATE : Messages.VM;
                Text = String.Format(Messages.CONFIRM_DELETE_TITLE, type);
            }
            else
            {
                Text = Messages.CONFIRM_DELETE_ITEMS_TITLE;
            }

            List <VDI> sharedVDIsCouldBeDelete = new List <VDI>();

            foreach (VM vm in vmList)
            {
                foreach (VBD vbd in vm.Connection.ResolveAll(vm.VBDs))
                {
                    if (!vbd.IsCDROM())
                    {
                        VDI vdi = vbd.Connection.Resolve(vbd.VDI);
                        if (vdi != null)
                        {
                            IList <VM> VMsUsingVDI         = vdi.GetVMs();
                            bool       allTheVMsAreDeleted = true;
                            if (VMsUsingVDI.Count > 1)
                            {
                                foreach (VM vmUsingVdi in VMsUsingVDI)
                                {
                                    if (!vmList.Contains(vmUsingVdi))
                                    {
                                        allTheVMsAreDeleted = false;
                                        break;
                                    }
                                }
                                if (allTheVMsAreDeleted && !sharedVDIsCouldBeDelete.Contains(vdi))
                                {
                                    sharedVDIsCouldBeDelete.Add(vdi);
                                }
                            }
                            else
                            {
                                ListViewItem item = new ListViewItem();
                                item.Text = vdi.Name();
                                item.SubItems.Add(vm.Name());
                                item.Group   = listView.Groups["listViewGroupAttachedDisks"];
                                item.Tag     = vbd;
                                item.Checked = vbd.GetIsOwner();
                                foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                                {
                                    subitem.Tag = subitem.Text;
                                }
                                listView.Items.Add(item);
                            }
                        }
                    }
                }

                foreach (VM snapshot in vm.Connection.ResolveAll(vm.snapshots))
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = snapshot.Name();
                    item.SubItems.Add(vm.Name());
                    item.Tag   = snapshot;
                    item.Group = listView.Groups["listViewGroupSnapshots"];
                    foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                    {
                        subitem.Tag = subitem.Text;
                    }
                    listView.Items.Add(item);
                }
            }
            foreach (VDI vdi in sharedVDIsCouldBeDelete)
            {
                ListViewItem item = new ListViewItem();
                item.Text = vdi.Name();
                item.SubItems.Add(vdi.VMsOfVDI());
                item.Group   = listView.Groups["listViewGroupAttachedDisks"];
                item.Tag     = vdi.Connection.ResolveAll(vdi.VBDs);
                item.Checked = false;
                foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                {
                    subitem.Tag = subitem.Text;
                }
                listView.Items.Add(item);
            }
            EnableSelectAllClear();
            EllipsizeStrings();
        }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, _updateName, sr.Name());
            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", _totalUpdateSize, sr.Name());

            VDI vdi    = NewVDI(sr);
            var vdiRef = VDI.create(Session, vdi);

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            string result;

            try
            {
                log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name(), sr.Name());

                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var sr1   = sr;
                    var descr = string.Format(Messages.UPLOAD_PATCH_UPLOADING_TO_SR_PROGRESS_DESCRIPTION, _updateName, sr1.Name(),
                                              Util.DiskSizeString(percent * _totalUpdateSize / 100, "F1"), Util.DiskSizeString(_totalUpdateSize));

                    var actionPercent = (int)((totalUploaded * 100 + percent) / totalCount);
                    ByteProgressDescription = descr;
                    Tick(actionPercent, descr);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "uploadTask", hostUrl);

                result = HTTPHelper.Put(progressDelegate, GetCancelling, true, Connection, RelatedTask, ref session, suppPackFilePath, hostUrl,
                                        (HTTP_actions.put_sss)HTTP_actions.put_import_raw_vdi,
                                        session.opaque_ref, vdiRef.opaque_ref);
            }
            catch (Exception ex)
            {
                log.Error("Failed to import a virtual disk over HTTP", ex);

                if (vdiRef != null)
                {
                    try
                    {
                        log.ErrorFormat("Deleting VDI '{0}' on a best effort basis.", vdiRef.opaque_ref);
                        Thread.Sleep(1000);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI.", removeEx);
                    }
                }

                //after having tried to remove the VDI, the original exception is thrown for the UI
                if (ex is TargetInvocationException && ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                Task.destroy(Session, RelatedTask);
                RelatedTask = null;
            }

            //introduce ISO for Ely and higher
            if (Helpers.ElyOrGreater(Connection))
            {
                try
                {
                    var poolUpdateRef = Pool_update.introduce(Connection.Session, vdiRef);
                    poolUpdate = Connection.WaitForCache(poolUpdateRef);

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                }
                catch (Exception ex)
                {
                    //clean-up the VDI we've just created
                    try
                    {
                        log.ErrorFormat("Deleting VDI '{0}' on a best effor basis.", vdiRef);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI", removeEx);
                    }

                    var failure = ex as Failure;
                    if (failure != null && failure.ErrorDescription != null && failure.ErrorDescription.Count > 1 && failure.ErrorDescription[0] == Failure.UPDATE_ALREADY_EXISTS)
                    {
                        string uuidFound = failure.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, StringComparison.InvariantCultureIgnoreCase));
                    }
                    else
                    {
                        log.Error("Failed to introduce the update", ex);
                        poolUpdate = null;
                        throw;
                    }
                }
            }
            else
            {
                poolUpdate = null;
            }

            if (localStorageHost != null)
            {
                VdiRefsPerHost.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefsPerHost.Add(server, vdiRef);
                }
            }

            totalUploaded++;
            Description = string.Format(Messages.SUPP_PACK_UPLOADED, sr.Name());

            foreach (Host host in servers)
            {
                SrsWithUploadedUpdatesPerHost[host] = sr;
            }

            return(result);
        }