Exemple #1
0
        public AttachUsbDialog(VM vm) : base(vm.Connection)
        {
            _vm           = vm;
            possibleHosts = new List <Host>();
            InitializeComponent();
            BuildList();
            treeUsbList_SelectedIndexChanged(null, null);

            DelegatedAsyncAction action = new DelegatedAsyncAction(_vm.Connection,
                                                                   string.Format(Messages.FETCH_POSSIBLE_HOSTS, _vm.Name()),
                                                                   string.Format(Messages.FETCHING_POSSIBLE_HOSTS, _vm.Name()),
                                                                   string.Format(Messages.FETCHED_POSSIBLE_HOSTS, _vm.Name()),
                                                                   delegate(Session session)
            {
                List <XenRef <Host> > possibleHostRefs = VM.get_possible_hosts(_vm.Connection.Session, _vm.opaque_ref);
                possibleHosts = _vm.Connection.ResolveAll(possibleHostRefs);
            },
                                                                   true);

            action.Completed += delegate
            {
                Program.Invoke(Program.MainWindow, BuildList);
            };
            action.RunAsync();
        }
Exemple #2
0
        private void testConnectionButton_Click(object sender, EventArgs e)
        {
            string password = textBoxPassword.Text.Trim();
            string address  = textBoxHostAddress.Text.Trim();
            string username = textBoxUsername.Text.Trim();

            string title = string.Format(Messages.STORAGELINK_TEST_CONNECTION, address);

            DelegatedAsyncAction action = null;

            action = new DelegatedAsyncAction(_xenObjectCopy.Connection, title, "", "", s =>
            {
                string secretUuid = Secret.CreateSecret(_xenObjectCopy.Connection.Session, password);
                var scanAction    = new SrCslgStorageSystemScanAction(Program.MainWindow, _xenObjectCopy.Connection, Program.StorageLinkConnections.GetCopy(), address, username, secretUuid);
                scanAction.RunExternal(action.Session);

                string secretRef = Secret.get_by_uuid(_xenObjectCopy.Connection.Session, secretUuid);
                Secret.destroy(_xenObjectCopy.Connection.Session, secretRef);
            }, true);

            action.AppliesTo.Add(_xenObjectCopy.opaque_ref);

            new ActionProgressDialog(action, ProgressBarStyle.Marquee).ShowDialog(this);

            passFailLabel.Visible    = true;
            passFailLabel.Text       = action.Succeeded ? Messages.CSLG_EDIT_CONNECTION_PASSED : Messages.CSLG_EDIT_CONNECTION_FAILED;
            passFailPictureBox.Image = action.Succeeded ? Resources._000_Tick_h32bit_16 : Resources._000_Abort_h32bit_16;
        }
Exemple #3
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            CustomFieldDefinition customFieldDefinition = lbCustomFields.SelectedItem as CustomFieldDefinition;

            if (customFieldDefinition == null)
            {
                return;
            }

            string name = customFieldDefinition.Name.Ellipsise(50);

            if (!MainWindow.Confirm(connection, Program.MainWindow, Messages.MESSAGEBOX_CONFIRM, Messages.MESSAGEBOX_DELETE_CUSTOM_FIELD, name))
            {
                return;
            }

            int selIdx = lbCustomFields.SelectedIndex;

            lbCustomFields.Items.RemoveAt(selIdx);
            DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
                                                                   String.Format(Messages.DELETE_CUSTOM_FIELD, name),
                                                                   String.Format(Messages.DELETING_CUSTOM_FIELD, name),
                                                                   String.Format(Messages.DELETED_CUSTOM_FIELD, name),
                                                                   delegate(Session session)
            {
                CustomFieldsManager.RemoveCustomField(session, connection, customFieldDefinition);
            });

            action.RunAsync();
        }
        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (tagsListView.SelectedItems.Count == 1)
            {
                string tag = tagsListView.SelectedItems[0].Text;

                ThreeButtonDialog tbd = new ThreeButtonDialog(
                    new ThreeButtonDialog.Details(SystemIcons.Warning, String.Format(Messages.CONFIRM_DELETE_TAG, tag), Messages.CONFIRM_DELETE_TAG_TITLE),
                    new ThreeButtonDialog.TBDButton(Messages.OK, DialogResult.OK),
                    ThreeButtonDialog.ButtonCancel);

                DialogResult result = tbd.ShowDialog(this);
                if (result != DialogResult.OK)
                {
                    return;
                }

                // Remove the tag from the tagsListView
                tagsListView.Items.Remove(tagsListView.SelectedItems[0]);
                setButtonEnablement();

                // Delete the tag from all resources on all servers
                DelegatedAsyncAction action = new DelegatedAsyncAction(null,
                                                                       String.Format(Messages.DELETE_ALL_TAG, tag),
                                                                       String.Format(Messages.DELETING_ALL_TAG, tag),
                                                                       String.Format(Messages.DELETED_ALL_TAG, tag),
                                                                       delegate(Session session)
                {
                    Tags.RemoveTagGlobally(tag);
                });
                action.RunAsync();
            }
        }
        private void LoadNetworks(Cluster cluster)
        {
            comboBoxNetwork.ExcludeNetworksWithoutIpAddresses = true;

            if (cluster == null)
            {
                comboBoxNetwork.PopulateComboBox(pool.Connection, item => false);
                if (comboBoxNetwork.Items.Count == 0)
                {
                    DisableControls(Messages.GFS2_NO_NETWORK);
                }
            }
            else
            {
                DelegatedAsyncAction action = new DelegatedAsyncAction(pool.Connection,
                                                                       string.Empty, string.Empty, string.Empty,
                                                                       delegate(Session session)
                {
                    commonNetwork = Cluster.get_network(session, cluster.opaque_ref);
                },
                                                                       true);

                action.Completed += action_Completed;

                action.RunAsync();
            }
        }
Exemple #6
0
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            var    vdi  = (VDI)selection[0].XenObject;
            string svid = vdi.sm_config["SVID"];
            var    storageLinkVolume = vdi.StorageLinkVolume(Program.StorageLinkConnections.GetCopy());
            string volumeName        = storageLinkVolume == null? "":storageLinkVolume.Name;

            var action = new DelegatedAsyncAction(
                vdi.Connection,
                string.Format(Messages.REMOVE_STORAGELINK_VOLUME_ACTION_TITLE, volumeName, _slr),
                string.Format(Messages.REMOVE_STORAGELINK_VOLUME_ACTION_START, volumeName, _slr),
                string.Format(Messages.REMOVE_STORAGELINK_VOLUME_ACTION_FINSH, volumeName, _slr),
                s => _slr.StorageLinkConnection.RemoveStorageVolumesFromStorageRepository(_slr, new[] { svid }));

            action.AppliesTo.Add(vdi.opaque_ref);
            action.AppliesTo.Add(svid);
            action.AppliesTo.Add(_slr.opaque_ref);

            SR sr = _slr.SR(ConnectionsManager.XenConnectionsCopy);

            if (sr != null)
            {
                action.AppliesTo.Add(sr.opaque_ref);
            }

            action.RunAsync();
        }
Exemple #7
0
        private void DestroyDrTasks()
        {
            // destroy DR tasks
            if (DrTasks.Count > 0)
            {
                SummaryReport.AddLine(Messages.DR_WIZARD_REPORT_DR_CLEANUP);
            }

            foreach (var drTask in DrTasks.ToList())
            {
                List <SR> srs     = Pool.Connection.ResolveAll(drTask.introduced_SRs);
                string    srNames = string.Join(", ", (from sr in srs select sr.Name()).ToArray());

                DR_task task   = drTask;
                var     action = new DelegatedAsyncAction(xenConnection,
                                                          string.Format(Messages.ACTION_DR_TASK_DESTROY_TITLE, srNames), Messages.ACTION_DR_TASK_DESTROY_STATUS, Messages.ACTION_DR_TASK_DESTROY_DONE,
                                                          s => DR_task.destroy(s, task.opaque_ref))
                {
                    Pool = this.Pool
                };
                new Dialogs.ActionProgressDialog(action, ProgressBarStyle.Blocks).ShowDialog();

                if (action.Succeeded)
                {
                    DrTasks.Remove(drTask);
                }

                SummaryReport.AddActionResult(action);
            }
        }
        private void CheckXenServerCredentials()
        {
            if (!CheckCredentialsEntered())
            {
                return;
            }

            bool passedRbacChecks       = false;
            DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
                                                                   Messages.CREDENTIALS_CHECKING, "", "",
                                                                   delegate
            {
                Session elevatedSession = null;
                try
                {
                    elevatedSession = connection.ElevatedSession(textboxXSUserName.Text.Trim(), textboxXSPassword.Text);
                    if (elevatedSession != null && (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession, Role.ValidRoleList("pool.set_health_check_config", connection))))
                    {
                        passedRbacChecks = true;
                    }
                }
                finally
                {
                    if (elevatedSession != null)
                    {
                        elevatedSession.Connection.Logout(elevatedSession);
                        elevatedSession = null;
                    }
                }
            },
                                                                   true);

            action.Completed += delegate
            {
                log.DebugFormat("Logging with the new credentials returned: {0} ", passedRbacChecks);
                Program.Invoke(Program.MainWindow, () =>
                {
                    if (passedRbacChecks)
                    {
                        ShowTestCredentialsStatus(Resources._000_Tick_h32bit_16, null);
                    }
                    else
                    {
                        ShowTestCredentialsStatus(Resources._000_error_h32bit_16, action.Exception != null ? action.Exception.Message : Messages.HEALTH_CHECK_USER_NOT_AUTHORIZED);
                    }
                    textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked;
                });
            };

            log.Debug("Testing logging in with the new credentials");
            ShowTestCredentialsStatus(Resources.ajax_loader, null);
            textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = false;
            action.RunAsync();
        }
        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);
        }
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            DelegatedAsyncAction action = new DelegatedAsyncAction(null,
                                                                   String.Format(Messages.RENAME_TAG, _oldName),
                                                                   String.Format(Messages.RENAMING_TAG, _oldName),
                                                                   String.Format(Messages.RENAMED_TAG, _oldName),
                                                                   delegate(Session session)
            {
                Tags.RenameTagGlobally(_oldName, _newName.Trim());
            });

            action.Completed += action_Completed;
            action.RunAsync();
        }
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            var pool = Helpers.GetPoolOfOne(selection.FirstAsXenObject.Connection);

            if (pool != null)
            {
                if (Helpers.FeatureForbidden(pool.Connection, Host.RestrictDR))
                {
                    ShowUpsellDialog(Parent);
                }
                else
                {
                    using (DRConfigureDialog dlog = new DRConfigureDialog(pool))
                    {
                        if (dlog.ShowDialog() == DialogResult.OK && (dlog.SRtoEnable.Count > 0 || dlog.SRtoDisable.Count > 0))
                        {
                            var actions = new List <AsyncAction>();

                            foreach (SR sr in dlog.SRtoDisable.Values)
                            {
                                SR  curSr  = sr;
                                var action = new DelegatedAsyncAction(pool.Connection,
                                                                      String.Format(Messages.ACTION_DR_DISABLING_ON, sr.Name), Messages.ACTION_DR_DISABLING, Messages.ACTION_DR_DISABLED,
                                                                      s => SR.disable_database_replication(s, curSr.opaque_ref))
                                {
                                    Pool = pool
                                };
                                actions.Add(action);
                            }

                            foreach (SR sr in dlog.SRtoEnable.Values)
                            {
                                SR  curSr  = sr;
                                var action = new DelegatedAsyncAction(pool.Connection,
                                                                      String.Format(Messages.ACTION_DR_ENABLING_ON, sr.Name), Messages.ACTION_DR_ENABLING, Messages.ACTION_DR_ENABLED,
                                                                      s => SR.enable_database_replication(s, curSr.opaque_ref))
                                {
                                    Pool = pool
                                };
                                actions.Add(action);
                            }

                            RunMultipleActions(actions, Messages.ACTION_DR_CONFIGURING, string.Empty, string.Empty, true);
                        }
                    }
                }
            }
        }
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            IStorageLinkObject sl     = (IStorageLinkObject)selection[0].XenObject;
            StorageLinkServer  server = sl.StorageLinkConnection.Cache.Server;

            if (server != null)
            {
                string address      = string.Empty;
                int    port         = 27000;
                var    getLicAction = new DelegatedAsyncAction(null,
                                                               string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_TITLE, server.FriendlyName),
                                                               string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_START, server.FriendlyName),
                                                               string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_TITLE, server.FriendlyName),
                                                               session => server.StorageLinkConnection.GetLicenseServer(out address, out port));
                new ActionProgressDialog(getLicAction, ProgressBarStyle.Marquee).ShowDialog(Parent ?? Program.MainWindow);

                if (!getLicAction.Succeeded)
                {
                    address = string.Empty;
                    port    = 27000;
                }

                var dialog = new SetStorageLinkLicenseServerDialog(address, port);

                dialog.FormClosing += (s, e) =>
                {
                    if (dialog.DialogResult == DialogResult.OK)
                    {
                        address = dialog.Host;
                        port    = dialog.Port;

                        var action = new DelegatedAsyncAction(null,
                                                              string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_TITLE, server.FriendlyName),
                                                              string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_START, server.FriendlyName),
                                                              string.Format(Messages.SET_STORAGELINK_LICENSE_SERVER_ACTION_TITLE, server.FriendlyName),
                                                              session => server.StorageLinkConnection.SetLicenseServer(address, port));

                        action.AppliesTo.Add(server.opaque_ref);

                        new ActionProgressDialog(action, ProgressBarStyle.Marquee).ShowDialog(Parent);
                        e.Cancel = !action.Succeeded;
                    }
                };

                dialog.Show(Parent ?? Program.MainWindow);
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            CustomFieldDefinition customFieldDefinition = lbCustomFields.SelectedItem as CustomFieldDefinition;

            if (customFieldDefinition == null)
            {
                return;
            }

            string name = customFieldDefinition.Name.Ellipsise(50);

            if (!Program.RunInAutomatedTestMode)
            {
                using (var dialog = new WarningDialog(string.Format(Messages.MESSAGEBOX_DELETE_CUSTOM_FIELD, name),
                                                      ThreeButtonDialog.ButtonYes, ThreeButtonDialog.ButtonNo)
                {
                    WindowTitle = Messages.MESSAGEBOX_CONFIRM
                })
                {
                    if (dialog.ShowDialog(Program.MainWindow) != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }

            if (connection != null && !connection.IsConnected)
            {
                MainWindow.ShowDisconnectedMessage(Program.MainWindow);
                return;
            }

            int selIdx = lbCustomFields.SelectedIndex;

            lbCustomFields.Items.RemoveAt(selIdx);
            DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
                                                                   String.Format(Messages.DELETE_CUSTOM_FIELD, name),
                                                                   String.Format(Messages.DELETING_CUSTOM_FIELD, name),
                                                                   String.Format(Messages.DELETED_CUSTOM_FIELD, name),
                                                                   delegate(Session session)
            {
                CustomFieldsManager.RemoveCustomField(session, connection, customFieldDefinition);
            });

            action.RunAsync();
        }
Exemple #14
0
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            var connections = new List <StorageLinkConnection>();

            foreach (IStorageLinkObject s in selection.AsXenObjects <IStorageLinkObject>())
            {
                if (!connections.Contains(s.StorageLinkConnection))
                {
                    connections.Add(s.StorageLinkConnection);
                }
            }

            foreach (StorageLinkConnection c in connections)
            {
                string title    = string.Format(Messages.REFRESH_STORAGELINK_SYSTEMS_ACTION_TITLE, c.Host);
                string startDes = Messages.REFRESH_STORAGELINK_SYSTEMS_ACTION_START;
                string endDes   = Messages.REFRESH_STORAGELINK_SYSTEMS_ACTION_END;

                var action = new DelegatedAsyncAction(null, title, startDes, endDes, s =>
                {
                    c.Refresh();

                    // wait for refresh to finish so the user can see that
                    // the refresh is still in progress in the logs tab.
                    for (int i = 0; i < 60 && c.RefreshInProgress; i++)
                    {
                        Thread.Sleep(500);
                    }
                });


                foreach (IStorageLinkObject s in selection.AsXenObjects <IStorageLinkObject>())
                {
                    if (s.StorageLinkConnection == c)
                    {
                        action.AppliesTo.Add(s.opaque_ref);
                    }
                }

                action.RunAsync();
            }
        }
        private void tagsListView_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            okButton.Enabled = true;

            TagsListViewItem itemRenaming = (TagsListViewItem)tagsListView.Items[e.Item];

            if (itemRenaming != null)
            {
                string oldName = itemRenaming.Text;
                string newName = (e.Label == null ? oldName : e.Label.Trim());   // null indicates no change

                if (newName == "")
                {
                    e.CancelEdit = true;
                    return;
                }

                foreach (TagsListViewItem currentItem in tagsListView.Items)
                {
                    if (currentItem != itemRenaming && currentItem.Text == newName)
                    {
                        e.CancelEdit = true;
                        return;
                    }
                }

                // Rename the tag in the list view ourselves (necessary if we've trimmed whitespace from the ends of the name)
                itemRenaming.Text = newName;
                e.CancelEdit      = true;

                // Rename the tag on all the servers
                DelegatedAsyncAction action = new DelegatedAsyncAction(null,
                                                                       String.Format(Messages.RENAME_TAG, oldName),
                                                                       String.Format(Messages.RENAMING_TAG, oldName),
                                                                       String.Format(Messages.RENAMED_TAG, oldName),
                                                                       delegate(Session session)
                {
                    Tags.RenameTagGlobally(oldName, newName);
                });
                action.RunAsync();
            }
        }
Exemple #16
0
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            List <AsyncAction> actions = new List <AsyncAction>();

            foreach (GroupingTag groupingTag in selection.AsGroupingTags())
            {
                string tag = groupingTag.Group.ToString();
                DelegatedAsyncAction action = new DelegatedAsyncAction(null,
                                                                       String.Format(Messages.DELETE_ALL_TAG, tag),
                                                                       String.Format(Messages.DELETING_ALL_TAG, tag),
                                                                       String.Format(Messages.DELETED_ALL_TAG, tag),
                                                                       delegate(Session session)
                {
                    Tags.RemoveTagGlobally(tag);
                });

                actions.Add(action);
            }

            RunMultipleActions(actions, Messages.DELETE_TAGS, Messages.DELETING_TAGS, Messages.DELETED_TAGS, true);
        }
        /// <summary>
        /// First prompts the user if there are any actions running, then cancels and d/c if they give the OK.
        /// </summary>
        /// <param name="connection"></param>
        /// <returns>True if the user agreed to d/c and cancel their tasks, false if we are going to remain connected</returns>
        private bool PromptAndDisconnectServer(IXenConnection connection)
        {
            if (!AllActionsFinished(connection, true))
            {
                if (MainWindowCommandInterface.RunInAutomatedTestMode ||
                    new CloseXenCenterWarningDialog(connection).ShowDialog(Parent) == DialogResult.OK)
                {
                    ConnectionsManager.CancelAllActions(connection);

                    DelegatedAsyncAction waitForCancelAction = new DelegatedAsyncAction(connection,
                                                                                        Messages.CANCELING_TASKS, Messages.CANCELING, Messages.COMPLETED,
                                                                                        delegate
                    {
                        DateTime startTime = DateTime.Now;
                        while ((DateTime.Now - startTime).TotalSeconds < 6.0)
                        {
                            if (AllActionsFinished(connection, false))
                            {
                                break;
                            }

                            Thread.Sleep(2000);
                        }
                    });

                    using (var pd = new ActionProgressDialog(waitForCancelAction, ProgressBarStyle.Marquee))
                    {
                        pd.ShowDialog(Parent);
                    }
                }
                else
                {
                    return(false);
                }
            }

            DoDisconnect(connection);
            return(true);
        }
Exemple #18
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            NewCustomFieldDialog dialog = new NewCustomFieldDialog(connection);

            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            CustomFieldDefinition definition = dialog.Definition;

            DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
                                                                   String.Format(Messages.ADD_CUSTOM_FIELD, definition.Name),
                                                                   String.Format(Messages.ADDING_CUSTOM_FIELD, definition.Name),
                                                                   String.Format(Messages.ADDED_CUSTOM_FIELD, definition.Name),
                                                                   delegate(Session session)
            {
                CustomFieldsManager.AddCustomField(session, connection, definition);
            });

            action.RunAsync();
        }
Exemple #19
0
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            NewSRWizard wizard = new NewSRWizard(Connection);

            wizard.CheckNFSISORadioButton();

            if (wizard.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            // Return if we lost connection
            if (Connection == null || Helpers.GetPoolOfOne(Connection) == null)
            {
                log.Error("Page_InstallationMedia: connection to the server was lost");
                return;
            }

            // There's a chance the cd radio button was disabled because we didnt have any isos to select from, so refresh that bool
            // and the enablement of that button.
            cds = Helpers.CDsExist(Connection);
            CdRadioButton.Enabled = (installed || installCd) && cds;

            // We can get a lot of refresh flickering in the ISO box as all the VDIs are discovered
            // Possibly slightly rude, but were going to have a pretend action here which gives it some breathing space before we look for VDIs
            DelegatedAsyncAction waitAction = new DelegatedAsyncAction(Connection, Messages.SR_REFRESH_ACTION_DESC, Messages.SR_REFRESH_ACTION_DESC, Messages.COMPLETED,
                                                                       delegate
            {
                System.Threading.Thread.Sleep(10000);
            }, true);

            using (var dlg = new ActionProgressDialog(waitAction, System.Windows.Forms.ProgressBarStyle.Marquee))
                dlg.ShowDialog(this);

            // Set the connection on the drop down iso box. This causes a complete refresh rather than a mini one - otherwise we miss out on
            // getting event handlers for the new SR
            CdDropDownBox.connection = Connection;
        }
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            StorageLinkRepository slr = selection[0].XenObject as StorageLinkRepository;

            if (slr == null)
            {
                var sr = selection[0].XenObject as SR;
                slr = sr != null?sr.StorageLinkRepository(Program.StorageLinkConnections) : null;
            }

            if (slr != null)
            {
                var dialog = new ImportStorageLinkVolumeDialog(slr);

                dialog.FormClosing += (s, e) =>
                {
                    if (dialog.DialogResult == DialogResult.OK)
                    {
                        var volumes = dialog.Volumes;
                        if (volumes.Count > 0)
                        {
                            var action = new DelegatedAsyncAction(null,
                                                                  string.Format(Messages.IMPORT_STORAGELINK_VOLUME_ACTION_TITLE, slr),
                                                                  string.Format(Messages.IMPORT_STORAGELINK_VOLUME_ACTION_START, slr),
                                                                  string.Format(Messages.IMPORT_STORAGELINK_VOLUME_ACTION_FINSH, slr),
                                                                  session => slr.StorageLinkConnection.AddStorageVolumesToStorageRepository(slr, volumes));

                            action.AppliesTo.Add(slr.opaque_ref);
                            action.AppliesTo.Add(slr.StorageLinkConnection.Cache.Server.opaque_ref);
                            action.RunAsync();
                        }
                    }
                };

                dialog.Show(Parent);
            }
        }
Exemple #21
0
        private void Scan()
        {
            //Save Evacuated VMs for later
            var saveVMsAction = new DelegatedAsyncAction(connection,
                                                         Messages.SAVING_VM_PROPERTIES_ACTION_TITLE, Messages.SAVING_VM_PROPERTIES_ACTION_DESC, Messages.COMPLETED,
                                                         session => _host.SaveEvacuatedVMs(session), true, "host.remove_from_other_config", "host.add_to_other_config");

            saveVMsAction.RunAsync(GetSudoElevationResult());

            vmErrorsAction = new DelegatedAsyncAction(connection, Messages.MAINTENANCE_MODE,
                                                      Messages.SCANNING_VMS, Messages.COMPLETED, delegate(Session session)
            {
                var cantEvacuateReasons = new Dictionary <XenRef <VM>, string[]>();

                if (Helpers.WlbEnabled(_host.Connection))
                {
                    try
                    {
                        cantEvacuateReasons = Host.retrieve_wlb_evacuate_recommendations(session, _host.opaque_ref);
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.Message, ex);
                    }
                }

                if (cantEvacuateReasons.Count == 0 || !ValidRecommendation(cantEvacuateReasons))
                {
                    cantEvacuateReasons = Host.get_vms_which_prevent_evacuation(session, _host.opaque_ref);
                }

                return(cantEvacuateReasons);
            }, true);

            vmErrorsAction.Completed += VmErrorsAction_Completed;
            vmErrorsAction.RunAsync(GetSudoElevationResult());
        }
Exemple #22
0
        protected override void ExecuteCore(SelectedItemCollection selection)
        {
            IXenObject selected = selection.FirstAsXenObject;
            var        server   = GetStorageLinkServer(selected);

            if (server == null)
            {
                return;
            }
            var dialog = new AddStorageLinkSystemDialog(server.StorageLinkConnection);
            var parent = Parent ?? (Control)Program.MainWindow;

            dialog.FormClosing += (s, e) =>
            {
                if (dialog.DialogResult == DialogResult.OK)
                {
                    var adapter  = dialog.StorageAdapter;
                    var port     = dialog.StorageSystemPort;
                    var address  = dialog.StorageSystemAddress;
                    var username = dialog.StorageSystemUsername;
                    var password = dialog.StorageSystemPassword;
                    var ns       = dialog.StorageSystemNamespace;

                    // There are no RBAC complexities here since only pool-operator and above can access the password for the storagelink service.
                    // Therefore only pool-operator and above can get here. These roles are permitted to add and remove storage systems.

                    var action = new StorageLinkDelegatedAsyncAction(
                        () => server.StorageLinkConnection.AddStorageSystem(adapter, port, address, username, password, ns),
                        string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_TITLE, address),
                        string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_START_DESCRIPTION, address),
                        string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_END_DESCRIPTION, address));

                    var actionWithWait = new DelegatedAsyncAction(null,
                                                                  string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_TITLE, address),
                                                                  string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_START_DESCRIPTION, address),
                                                                  string.Format(Messages.ADD_STORAGE_LINK_SYSTEM_ACTION_END_DESCRIPTION, address), ss =>
                    {
                        int storageSystemCountBefore = server.StorageLinkConnection.Cache.StorageSystems.Count;
                        action.RunExternal(ss);

                        for (int i = 0; i < 60 && action.Succeeded && server.StorageLinkConnection.Cache.StorageSystems.Count == storageSystemCountBefore; i++)
                        {
                            if ((i % 5) == 0)
                            {
                                log.Info("Waiting for StorageLink storage-system to be added to cache.");
                            }

                            Thread.Sleep(500);
                        }
                    }, true);

                    actionWithWait.AppliesTo.Add(server.opaque_ref);
                    actionWithWait.Completed += ss => OnCompleted(new CompletedEventArgs(actionWithWait.Succeeded));

                    new ActionProgressDialog(actionWithWait, ProgressBarStyle.Continuous)
                    {
                        ShowCancel = true
                    }.ShowDialog(dialog);

                    // keep creds dialog open if it failed.
                    e.Cancel = !actionWithWait.Succeeded;
                }
            };

            dialog.Show(parent);
        }
        private void CheckXenServerCredentials()
        {
            if (string.IsNullOrEmpty(textboxXSUserName.Text.Trim()) || string.IsNullOrEmpty(textboxXSPassword.Text))
            {
                return;
            }

            bool passedRbacChecks       = false;
            DelegatedAsyncAction action = new DelegatedAsyncAction(connection,
                                                                   Messages.CREDENTIALS_CHECKING, "", "",
                                                                   delegate
            {
                Session elevatedSession = null;
                try
                {
                    elevatedSession = connection.ElevatedSession(textboxXSUserName.Text.Trim(), textboxXSPassword.Text);
                    if (elevatedSession != null && (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession, Role.ValidRoleList("pool.set_health_check_config", connection))))
                    {
                        passedRbacChecks = true;
                    }
                }
                catch (Failure f)
                {
                    if (f.ErrorDescription.Count > 0 && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                    {
                        // we use a different error message here from the standard one in friendly names
                        throw new Exception(Messages.HEALTH_CHECK_USER_HAS_NO_PERMISSION_TO_CONNECT);
                    }
                    throw;
                }
                finally
                {
                    if (elevatedSession != null)
                    {
                        elevatedSession.Connection.Logout(elevatedSession);
                        elevatedSession = null;
                    }
                }
            },
                                                                   true);

            action.Completed += delegate
            {
                log.DebugFormat("Logging with the new credentials returned: {0} ", passedRbacChecks);
                Program.Invoke(Program.MainWindow, () =>
                {
                    if (passedRbacChecks)
                    {
                        ShowTestCredentialsStatus(Resources._000_Tick_h32bit_16, null);
                    }
                    else
                    {
                        ShowTestCredentialsStatus(Resources._000_error_h32bit_16, action.Exception != null ? action.Exception.Message : Messages.HEALTH_CHECK_USER_NOT_AUTHORIZED);
                    }
                    textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked;
                });
            };

            log.Debug("Testing logging in with the new credentials");
            ShowTestCredentialsStatus(Resources.ajax_loader, null);
            textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = false;
            action.RunAsync();
        }
Exemple #24
0
        private void Scan()
        {
            DelegatedAsyncAction saveVMsAction = new DelegatedAsyncAction(connection, Messages.SAVING_VMS_ACTION_TITLE,
                                                                          Messages.SAVING_VMS_ACTION_DESC, Messages.COMPLETED, delegate(Session session)
            {
                //Save Evacuated VMs for later
                host.SaveEvacuatedVMs(session);
            }, "host.remove_from_other_config", "host.add_to_other_config");

            DelegatedAsyncAction action = new DelegatedAsyncAction(connection, Messages.MAINTENANCE_MODE,
                                                                   Messages.SCANNING_VMS, Messages.SCANNING_VMS, delegate(Session session)
            {
                reasons = new Dictionary <XenRef <VM>, string[]>();

                // WLB: get host wlb evacuate recommendation if wlb is enabled
                if (Helpers.WlbEnabled(host.Connection))
                {
                    try
                    {
                        reasons = XenAPI.Host.retrieve_wlb_evacuate_recommendations(session, host.opaque_ref);
                    }
                    catch (Exception ex)
                    {
                        log.Debug(ex.Message, ex);
                    }
                }


                // WLB: in case wlb has no recommendations or get errors when retrieve recommendation,
                //      assume retrieve_wlb_evacuate_recommendations returns 0 recommendation
                //      or return recommendations for all running vms on this host
                if (reasons.Count == 0 || !ValidRecommendation(reasons))
                {
                    reasons = Host.get_vms_which_prevent_evacuation(session, host.opaque_ref);
                }

                // take care of errors
                Program.Invoke(this, delegate()
                {
                    foreach (KeyValuePair <XenRef <VM>, String[]> kvp in reasons)
                    {
                        //WLB: filter out errors
                        if (string.Compare(kvp.Value[0].Trim(), "wlb", true) != 0)
                        {
                            ProcessError(kvp.Key.opaque_ref, kvp.Value);
                        }

                        //Update NewMasterComboBox for host power on recommendation
                        if ((session.Connection.Resolve(kvp.Key)).is_control_domain)
                        {
                            Host powerOnHost = session.Connection.Cache.Find_By_Uuid <Host>(kvp.Value[(int)RecProperties.ToHost]);
                            if (powerOnHost != null)
                            {
                                var previousSelection = NewMasterComboBox.SelectedItem as ToStringWrapper <Host>;
                                var hostToAdd         = new ToStringWrapper <Host>(powerOnHost, powerOnHost.Name());
                                if (NewMasterComboBox.Items.Count == 0)
                                {
                                    powerOnHost.PropertyChanged -= new PropertyChangedEventHandler(host_PropertyChanged);
                                    powerOnHost.PropertyChanged += new PropertyChangedEventHandler(host_PropertyChanged);
                                    NewMasterComboBox.Items.Add(hostToAdd);
                                }
                                else
                                {
                                    foreach (ToStringWrapper <Host> tswh in NewMasterComboBox.Items)
                                    {
                                        if (tswh.item.CompareTo(powerOnHost) != 0)
                                        {
                                            powerOnHost.PropertyChanged -= new PropertyChangedEventHandler(host_PropertyChanged);
                                            powerOnHost.PropertyChanged += new PropertyChangedEventHandler(host_PropertyChanged);
                                            NewMasterComboBox.Items.Add(hostToAdd);
                                        }
                                    }
                                }
                                SelectProperItemInNewMasterComboBox(previousSelection);
                            }
                        }
                    }
                });
            }, true);

            SetSession(saveVMsAction);
            SetSession(action);
            saveVMsAction.RunAsync();
            using (var dlg = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
                dlg.ShowDialog(this);
            RefreshEntermaintenanceButton();
        }
Exemple #25
0
            private void updateCell(int index)
            {
                switch (index)
                {
                case 0:
                    Cells[0].Value = pif.Name();
                    break;

                case 1:
                    Cells[1].Value = pif.MAC;
                    break;

                case 2:
                    Cells[2].Value = pif.Carrier() ? Messages.CONNECTED : Messages.DISCONNECTED;
                    break;

                case 3:
                    Cells[3].Value = pif.Carrier() ? pif.Speed() : Messages.HYPHEN;
                    break;

                case 4:
                    Cells[4].Value = pif.Carrier() ? pif.Duplex() : Messages.HYPHEN;
                    break;

                case 5:
                    Cells[5].Value = vendor;
                    break;

                case 6:
                    Cells[6].Value = device;
                    break;

                case 7:
                    Cells[7].Value = busPath;
                    break;

                case 8:
                    Cells[8].Value = pif.FCoECapable().ToYesNoStringI18n();
                    break;

                case 9:
                    string sriovSupported = "";
                    if (!pif.SriovCapable() || !pif.IsSriovPhysicalPIF())
                    {
                        sriovSupported = !pif.SriovCapable() ? Messages.NO : Messages.SRIOV_DISABLED;
                        Cells[9].Value = sriovSupported;
                    }
                    else
                    {
                        DelegatedAsyncAction action = new DelegatedAsyncAction(pif.Connection,
                                                                               "", "", "",
                                                                               delegate(Session session)
                        {
                            try
                            {
                                var remainingCapacity = Network_sriov.get_remaining_capacity(session, pif.sriov_physical_PIF_of[0].opaque_ref);
                                sriovSupported        = string.Format(Messages.REAMININF_VFS, remainingCapacity);
                            }
                            catch
                            {
                                sriovSupported = Messages.YES;
                            }
                        },
                                                                               true);

                        action.Completed += delegate
                        {
                            Program.Invoke(Program.MainWindow, delegate { Cells[9].Value = sriovSupported; });
                        };
                        action.RunAsync();
                    }

                    break;
                }
            }
Exemple #26
0
        private void ButtonLogout_Click(object sender, EventArgs e)
        {
            Program.AssertOnEventThread();
            // Double check, this method is called from a context menu as well and the state could have changed under it
            if (!ButtonLogout.Enabled)
            {
                return;
            }

            Session session = _connection.Session;

            if (session == null)
            {
                return;
            }

            // First we check through the list to check what warning message we show
            List <Subject> subjectsToLogout = new List <Subject>();

            foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows)
            {
                if (r.IsLocalRootRow || !r.LoggedIn)
                {
                    continue;
                }

                subjectsToLogout.Add(r.subject);
            }

            bool suicide = false;

            // Warn if user is logging themselves out
            if (session.Subject != null)//have already checked session not null
            {
                var warnMsg = string.Format(subjectsToLogout.Count > 1 ? Messages.AD_LOGOUT_SUICIDE_MANY : Messages.AD_LOGOUT_SUICIDE_ONE,
                                            Helpers.GetName(_connection).Ellipsise(50));

                foreach (Subject entry in subjectsToLogout)
                {
                    if (entry.opaque_ref == session.Subject)
                    {
                        DialogResult r;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(
                                       SystemIcons.Warning,
                                       warnMsg,
                                       Messages.AD_FEATURE_NAME),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            r = dlg.ShowDialog(this);
                        }

                        //CA-64818: DialogResult can be No if the No button has been hit
                        //or Cancel if the dialog has been closed from the control box
                        if (r != DialogResult.Yes)
                        {
                            return;
                        }

                        suicide = true;
                        break;
                    }
                }
            }

            var logoutMessage = subjectsToLogout.Count == 1
                ? string.Format(Messages.QUESTION_LOGOUT_AD_USER_ONE, subjectsToLogout[0].DisplayName ?? subjectsToLogout[0].SubjectName)
                : string.Format(Messages.QUESTION_LOGOUT_AD_USER_MANY, subjectsToLogout.Count);

            if (!suicide)//CA-68645
            {
                DialogResult questionDialog;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Warning,
                               logoutMessage,
                               Messages.AD_FEATURE_NAME),
                           ThreeButtonDialog.ButtonYes,
                           new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                {
                    questionDialog = dlg.ShowDialog(this);
                }

                //CA-64818: DialogResult can be No if the No button has been hit
                //or Cancel if the dialog has been closed from the control box
                if (questionDialog != DialogResult.Yes)
                {
                    return;
                }
            }

            // Then we go through the list and disconnect each user session, doing our own last if necessary
            foreach (AdSubjectRow r in GridViewSubjectList.SelectedRows)
            {
                // check they are not the root row and are logged in
                if (r.IsLocalRootRow || !r.LoggedIn)
                {
                    continue;
                }

                if (session.UserSid == r.subject.subject_identifier)
                {
                    continue;
                }
                DelegatedAsyncAction logoutAction = new DelegatedAsyncAction(_connection, Messages.TERMINATING_SESSIONS, Messages.IN_PROGRESS, Messages.COMPLETED, delegate(Session s)
                {
                    Session.logout_subject_identifier(s, r.subject.subject_identifier);
                }, "session.logout_subject_identifier");
                logoutAction.RunAsync();
            }
            if (suicide)
            {
                DelegatedAsyncAction logoutAction = new DelegatedAsyncAction(_connection, Messages.TERMINATING_SESSIONS, Messages.IN_PROGRESS, Messages.COMPLETED, delegate(Session s)
                {
                    Session.logout_subject_identifier(s, session.UserSid);
                    _connection.Logout();
                }, "session.logout_subject_identifier");
                logoutAction.RunAsync();
            }
            else
            {
                // signal the background thread to update the logged in status
                lock (statusUpdaterLock)
                    Monitor.Pulse(statusUpdaterLock);
            }
        }
        private void buttonAuthorize_Click(object sender, EventArgs e)
        {
            try
            {
                Exception delegateException = null;
                log.Debug("Testing logging in with the new credentials");
                DelegatedAsyncAction loginAction = new DelegatedAsyncAction(connection,
                                                                            Messages.AUTHORIZING_USER,
                                                                            Messages.CREDENTIALS_CHECKING,
                                                                            Messages.CREDENTIALS_CHECK_COMPLETE,
                                                                            delegate
                {
                    try
                    {
                        elevatedSession = connection.ElevatedSession(TextBoxUsername.Text.Trim(), TextBoxPassword.Text);
                    }
                    catch (Exception ex)
                    {
                        delegateException = ex;
                    }
                });

                using (var dlg = new ActionProgressDialog(loginAction, ProgressBarStyle.Marquee, false))
                    dlg.ShowDialog(this);

                // The exception would have been handled by the action progress dialog, just return the user to the sudo dialog
                if (loginAction.Exception != null)
                {
                    return;
                }

                if (HandledAnyDelegateException(delegateException))
                {
                    return;
                }

                if (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession))
                {
                    elevatedUsername = TextBoxUsername.Text.Trim();
                    elevatedPassword = TextBoxPassword.Text;
                    DialogResult     = DialogResult.OK;
                    Close();
                    return;
                }

                ShowNotAuthorisedDialog();
            }
            catch (Exception ex)
            {
                log.DebugFormat("Exception when attempting to sudo action: {0} ", ex);
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(
                               SystemIcons.Error,
                               String.Format(Messages.USER_AUTHORIZATION_FAILED, TextBoxUsername.Text),
                               Messages.XENCENTER)))
                {
                    dlg.ShowDialog(Parent);
                }

                TextBoxPassword.Focus();
                TextBoxPassword.SelectAll();
            }
            finally
            {
                // Check whether we have a successful elevated session and whether we have been asked to log it out
                // If non successful (most likely the new subject is not authorized) then log it out anyway.
                if (elevatedSession != null && DialogResult != DialogResult.OK)
                {
                    elevatedSession.Connection.Logout(elevatedSession);
                    elevatedSession = null;
                }
            }
        }
        protected override void Run()
        {
            if (vmOptList.Count == 0)
            {
                log.ErrorFormat("{0} has no VMs need to be optimized", Helpers.GetName(Pool));
                return;
            }

            this.Description = Messages.ACTION_WLB_POOL_OPTIMIZING;

            try
            {
                log.Debug("Optimizing " + Pool.Name());

                // for checking whether to display recommendations on optimize pool listview
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.IN_PROGRESS);
                int start = 0;
                int each  = 90 / vmOptList.Count;

                foreach (KeyValuePair <VM, WlbOptimizationRecommendation> vmItem in vmOptList)
                {
                    VM vm = vmItem.Key;

                    if (vmItem.Key.is_control_domain)
                    {
                        log.Debug(vmItem.Value.powerOperation + " " + Helpers.GetName(vmItem.Value.toHost));
                        Host fromHost = vmItem.Value.fromHost;
                        Helpers.SetOtherConfig(fromHost.Connection.Session, fromHost, WlbOptimizationRecommendation.OPTIMIZINGPOOL, vmItem.Value.recId.ToString());

                        AsyncAction hostAction      = null;
                        int         waitingInterval = 10 * 1000; // default to 10s

                        if (vmItem.Value.fromHost.IsLive())
                        {
                            hostAction = new ShutdownHostAction(fromHost, AddHostToPoolCommand.NtolDialog);
                        }
                        else
                        {
                            hostAction      = new HostPowerOnAction(fromHost);
                            waitingInterval = 30 * 1000;     // wait for 30s
                        }

                        hostAction.Completed += HostAction_Completed;
                        hostAction.RunAsync();

                        while (!moveToNext)
                        {
                            if (!String.IsNullOrEmpty(hostActionError))
                            {
                                throw new Exception(hostActionError);
                            }
                            else
                            {
                                //wait
                                System.Threading.Thread.Sleep(waitingInterval);
                            }
                        }
                    }
                    else
                    {
                        log.Debug("Migrating VM " + vm.Name());
                        Host toHost = vmItem.Value.toHost;

                        try
                        {
                            // check if there is a conflict with HA, start optimize if we can
                            RelocateVmWithHa(this, vm, toHost, start, start + each, vmItem.Value.recId);
                        }
                        catch (Failure f)
                        {
                            // prompt to user if ha notl can be raised, if yes, continue
                            long newNtol;
                            if (RaiseHANotl(vm, f, out newNtol))
                            {
                                DelegatedAsyncAction action = new DelegatedAsyncAction(vm.Connection, Messages.HA_LOWERING_NTOL, null, null,
                                                                                       delegate(Session session)
                                {
                                    // Set new ntol, then retry action
                                    XenAPI.Pool.set_ha_host_failures_to_tolerate(session, this.Pool.opaque_ref, newNtol);
                                    // ntol set succeeded, start new action
                                    Program.MainWindow.CloseActiveWizards(vm);
                                    new VMMigrateAction(vm, toHost).RunAsync();
                                });
                                action.RunAsync();
                            }
                            else
                            {
                                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.WLB_OPT_FAILED);
                                this.Description = Messages.WLB_OPT_FAILED;
                                throw;
                            }
                        }
                    }
                    start += each;

                    // stop if user cancels optimize pool
                    if (Cancelling)
                    {
                        throw new CancelledException();
                    }
                }
                this.Description = Messages.WLB_OPT_OK_NOTICE_TEXT;
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                log.Debug("Completed optimizing " + Pool.Name());
            }
            catch (Failure ex)
            {
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, ex);
                throw;
            }
            catch (CancelledException)
            {
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex, ex);
                this.Description = Messages.WLB_OPT_FAILED;
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                log.Debug("Optimizing " + Pool.Name() + " is failed");
            }
            this.PercentComplete = 100;
        }
Exemple #29
0
        /// <summary>
        /// In the case there being nowhere to start/resume the VM (NO_HOSTS_AVAILABLE), shows the reason why the VM could not be started
        /// on each host. If the start failed due to HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN, offers to decrement ntol and try the operation
        /// again.
        /// </summary>
        /// <param name="vm"></param>
        /// <param name="f"></param>
        /// <param name="kind">The kind of the operation that failed. Must be one of Start/StartOn/Resume/ResumeOn.</param>
        public static void StartDiagnosisForm(VMStartAbstractAction VMStartAction, Failure failure)
        {
            if (failure.ErrorDescription[0] == Failure.NO_HOSTS_AVAILABLE)
            {
                // Show a dialog displaying why the VM couldn't be started on each host
                StartDiagnosisForm(VMStartAction.VM, VMStartAction.IsStart);
            }
            else if (failure.ErrorDescription[0] == Failure.HA_OPERATION_WOULD_BREAK_FAILOVER_PLAN)
            {
                // The action was blocked by HA because it would reduce the number of tolerable server failures.
                // With the user's consent, we'll reduce the number of configured failures to tolerate and try again.
                Pool pool = Helpers.GetPool(VMStartAction.VM.Connection);
                if (pool == null)
                {
                    log.ErrorFormat("Could not get pool for VM {0} in StartDiagnosisForm()", Helpers.GetName(VMStartAction.VM));
                    return;
                }

                long ntol    = pool.ha_host_failures_to_tolerate;
                long newNtol = Math.Min(pool.ha_plan_exists_for - 1, ntol - 1);
                if (newNtol <= 0)
                {
                    // We would need to basically turn HA off to start this VM
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_ZERO : Messages.HA_VM_RESUME_NTOL_ZERO,
                                               Helpers.GetName(pool).Ellipsise(100),
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100));
                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        using (var dlg = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY)))
                        {
                            dlg.ShowDialog(Program.MainWindow);
                        }
                    });
                }
                else
                {
                    // Show 'reduce ntol?' dialog
                    string msg = String.Format(VMStartAction.IsStart ? Messages.HA_VM_START_NTOL_DROP : Messages.HA_VM_RESUME_NTOL_DROP,
                                               Helpers.GetName(pool).Ellipsise(100), ntol,
                                               Helpers.GetName(VMStartAction.VM).Ellipsise(100), newNtol);

                    Program.Invoke(Program.MainWindow, delegate()
                    {
                        DialogResult r;
                        using (var dlg = new ThreeButtonDialog(
                                   new ThreeButtonDialog.Details(SystemIcons.Warning, msg, Messages.HIGH_AVAILABILITY),
                                   ThreeButtonDialog.ButtonYes,
                                   new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, ThreeButtonDialog.ButtonType.CANCEL, true)))
                        {
                            r = dlg.ShowDialog(Program.MainWindow);
                        }

                        if (r == DialogResult.Yes)
                        {
                            DelegatedAsyncAction action = new DelegatedAsyncAction(VMStartAction.VM.Connection, Messages.HA_LOWERING_NTOL, null, null,
                                                                                   delegate(Session session)
                            {
                                // Set new ntol, then retry action
                                XenAPI.Pool.set_ha_host_failures_to_tolerate(session, pool.opaque_ref, newNtol);
                                // ntol set succeeded, start new action
                                VMStartAction.Clone().RunAsync();
                            });
                            action.RunAsync();
                        }
                    });
                }
            }
        }
        protected override void Run()
        {
            if (vmOptList.Count == 0)
            {
                log.ErrorFormat("{0} has no VMs need to be optimized", Helpers.GetName(Pool));
                return;
            }

            this.Description = Messages.ACTION_WLB_POOL_OPTIMIZING;

            try
            {
                log.Debug("Optimizing " + Pool.Name);

                // for checking whether to display recommendations on optimize pool listview
                Helpers.SetOtherConfig(this.Session, this.Pool,WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.IN_PROGRESS);
                int start = 0;
                int each = 90 / vmOptList.Count;

                foreach (KeyValuePair<VM, WlbOptimizationRecommendation> vmItem in vmOptList)
                {
                        VM vm = vmItem.Key;
                        Host fromHost = null;
                        Host toHost = null;

                        if (vmItem.Key.is_control_domain)
                        {
                            log.Debug(vmItem.Value.powerOperation + " " + Helpers.GetName(vmItem.Value.toHost));
                            fromHost = vmItem.Value.fromHost;
                            Helpers.SetOtherConfig(fromHost.Connection.Session, fromHost,WlbOptimizationRecommendation.OPTIMIZINGPOOL, vmItem.Value.recId.ToString());

                            try
                            {
                                AsyncAction hostAction = null;
                                int waitingInterval = 10 * 1000; // default to 10s

                                if (vmItem.Value.fromHost.IsLive)
                                {
                                    hostAction = new ShutdownHostAction(fromHost,AddHostToPoolCommand.NtolDialog);
                                }
                                else
                                {
                                    hostAction = new HostPowerOnAction(fromHost);
                                    waitingInterval = 30 * 1000; // wait for 30s
                                }

                                hostAction.Completed += HostAction_Completed;
                                hostAction.RunAsync();

                                while (!moveToNext)
                                {
                                    if (!String.IsNullOrEmpty(hostActionError))
                                    {
                                        throw new Exception(hostActionError);
                                    }
                                    else
                                    {
                                        //wait
                                        System.Threading.Thread.Sleep(waitingInterval);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                        else
                        {
                            log.Debug("Migrating VM " + vm.Name);
                            fromHost = this.Pool.Connection.Resolve(vm.resident_on);
                            toHost = vmItem.Value.toHost;

                            try
                            {

                                // check if there is a conflict with HA, start optimize if we can
                                RelocateVmWithHa(this, vm, toHost, start, start + each, vmItem.Value.recId);
                            }
                            catch (Failure f)
                            {
                                // prompt to user if ha notl can be raised, if yes, continue
                                long newNtol = 0;
                                if (RaiseHANotl(vm, f, out newNtol))
                                {
                                    DelegatedAsyncAction action = new DelegatedAsyncAction(vm.Connection, Messages.HA_LOWERING_NTOL, null, null,
                                        delegate(Session session)
                                    {
                                        // Set new ntol, then retry action
                                        XenAPI.Pool.set_ha_host_failures_to_tolerate(session, this.Pool.opaque_ref, newNtol);
                                        // ntol set succeeded, start new action
                                        Program.MainWindow.closeActiveWizards(vm);
                                        new VMMigrateAction(vm,toHost).RunAsync();
                                    });
                                    action.RunAsync();
                                }
                                else
                                {
                                    Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, Messages.WLB_OPT_FAILED);
                                    this.Description = Messages.WLB_OPT_FAILED;
                                    throw f;
                                }
                            }
                        }
                        start += each;

                        // stop if user cancels optimize pool
                        if (Cancelling)
                            throw new CancelledException();
                    }
                    this.Description = Messages.WLB_OPT_OK_NOTICE_TEXT;
                    Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                    log.Debug("Completed optimizing " + Pool.Name);
                }
            catch (Failure ex)
            {
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                WlbServerState.SetState(Pool, WlbServerState.ServerState.ConnectionError, (Failure)ex);
                throw;
            }
            catch (CancelledException)
            {
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex, ex);
                this.Description = Messages.WLB_OPT_FAILED;
                Helpers.SetOtherConfig(this.Session, this.Pool, WlbOptimizationRecommendation.OPTIMIZINGPOOL, optId);
                log.Debug("Optimizing " + Pool.Name + " is failed");
            }
            this.PercentComplete = 100;
        }
Exemple #31
0
            private void Update()
            {
                _cellName.Value      = Pif.Name();
                _cellMac.Value       = Pif.MAC;
                _cellConnected.Value = Pif.Carrier() ? Messages.CONNECTED : Messages.DISCONNECTED;
                _cellSpeed.Value     = Pif.Carrier() ? Pif.Speed() : Messages.HYPHEN;
                _cellDuplex.Value    = Pif.Carrier() ? Pif.Duplex() : Messages.HYPHEN;

                var pifMetrics = Pif.PIFMetrics();

                _cellVendor.Value  = pifMetrics == null ? Messages.HYPHEN : pifMetrics.vendor_name;
                _cellDevice.Value  = pifMetrics == null ? Messages.HYPHEN : pifMetrics.device_name;
                _cellBusPath.Value = pifMetrics == null ? Messages.HYPHEN : pifMetrics.pci_bus_path;

                _cellFcoe.Value = Pif.FCoECapable().ToYesNoStringI18n();

                if (!Pif.SriovCapable())
                {
                    _cellSriov.Value = Messages.NO;
                }
                else if (!Pif.IsSriovPhysicalPIF())
                {
                    _cellSriov.Value = Messages.SRIOV_NETWORK_SHOULD_BE_CREATED;
                }
                else
                {
                    var networkSriov = Pif.Connection.Resolve(Pif.sriov_physical_PIF_of[0]);

                    if (networkSriov == null || networkSriov.requires_reboot)
                    {
                        _cellSriov.Value = Messages.HOST_NEEDS_REBOOT_ENABLE_SRIOV;
                        return;
                    }

                    PIF sriovLogicalPif = Pif.Connection.Resolve(networkSriov.logical_PIF);

                    if (sriovLogicalPif == null || !sriovLogicalPif.currently_attached)
                    {
                        _cellSriov.Value = Messages.SRIOV_LOGICAL_PIF_UNPLUGGED;
                        return;
                    }

                    var sriovSupported = "";
                    var action         = new DelegatedAsyncAction(Pif.Connection, "", "", "", delegate(Session session)
                    {
                        try
                        {
                            var remainingCapacity = Network_sriov.get_remaining_capacity(session, Pif.sriov_physical_PIF_of[0].opaque_ref);
                            sriovSupported        = string.Format(Messages.REMAINING_VFS, remainingCapacity);
                        }
                        catch
                        {
                            sriovSupported = Messages.YES;
                        }
                    },
                                                                  true);

                    action.Completed += delegate
                    {
                        Program.Invoke(Program.MainWindow, () => _cellSriov.Value = sriovSupported);
                    };
                    action.RunAsync();
                }
            }