private void CreateNewConnection(string dbFileName, string username, string password) { string fileName = TestResource(dbFileName); Assert.True(File.Exists(fileName), String.Format("Provided filename does not exist: '{0}'. " + "If this is a new file, maybe the 'Copy To Ouput Directory' property has not been set", fileName)); XenAdminConfigManager.Provider = new TestXenAdminConfigProvider(); IXenConnection connection = new XenConnection(fileName, dbFileName); ServicePointManager.DefaultConnectionLimit = 20; ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate; Session session = connection.Connect(username, password); Assert.NotNull(session); connection.LoadCache(session); Assert.True(connection.CacheIsPopulated); lock (ConnectionListLock) { if (connections.ContainsKey(dbFileName)) { connections.Remove(dbFileName); } connections.Add(dbFileName, connection); } }
private void buttonAddNewServer_Click(object sender, EventArgs e) { IXenConnection newConnection = new XenConnection(); newConnections.Add(newConnection); new AddServerTask(this, newConnection, null).Start(); }
/// <param name="connection">May be null, in which case a new connection will be created</param> protected void ConnectToServer(IXenConnection conn, string hostname, int port, string username, string password, string version) { if (conn == null) { XenConnection connection = new XenConnection(); connection.CachePopulated += conn_CachePopulated; connection.fromDialog = true; conn = connection; } else if (!_changedPass) { conn.EndConnect(); // in case we're already connected } conn.Hostname = hostname; conn.Port = port; conn.Username = username; conn.Password = password; conn.ExpectPasswordIsCorrect = false; conn.Version = version; if (!_changedPass) { XenConnectionUI.BeginConnect(conn, true, Owner, false); } }
private TreeNode AddHostNode(TreeNode parent, int index, XenConnection connection, Host host, out bool expand, out bool live) { Host_metrics host_metrics = host.Connection.Resolve <Host_metrics>(host.metrics); live = (host_metrics != null) && host_metrics.live; return(this.AddNode(parent, index, host.name_label, Images.GetIconFor(host), false, host, out expand)); }
protected void DeleteOrMove(List <IXenObject> objects, Folder folder, Func <bool> cancelling) { XenConnection connection = null; if (objects.Count > 0) { connection = objects[0].Connection as XenConnection; } connection?.OnBeforeMajorChange(true); try { foreach (var obj in objects) { DeleteOrMove(obj, folder, cancelling); } // Update EMPTY_FOLDERS on all servers UpdateEmptyFolders(cancelling); } finally { connection?.OnAfterMajorChange(true); } }
internal void SettingValue(List <VM> vmCheckedList, Dictionary <string, string> vdiCheckedList, XenConnection _selected_xenConnection, Host _selected_host, string _selected_sr_uuid) { this.vmCheckedList = vmCheckedList; this.vdiCheckedDic = vdiCheckedList; this.selected_xenConnection = _selected_xenConnection; this.selected_host = _selected_host; this.selected_sr_uuid = _selected_sr_uuid; }
protected override void ExecuteCore(SelectedItemCollection selection) { List <AsyncAction> actions = new List <AsyncAction>(); foreach (Host host in selection.AsXenObjects <Host>()) { string opaque_ref = host.opaque_ref; Pool pool = Helpers.GetPool(host.Connection); if (selection.Count == 1 && pool.master == host.opaque_ref) { // Trying to remove the master from a pool. using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, Messages.MESSAGEBOX_POOL_MASTER_REMOVE, Messages.XENCENTER))) { dlg.ShowDialog(MainWindowCommandInterface.Form); } return; } // Optimistically, add the ejected host as a standalone host (but don't connect to it yet) IXenConnection connection = new XenConnection(); connection.Hostname = host.address; connection.Username = host.Connection.Username; connection.Password = host.Connection.Password; connection.FriendlyName = host.Name(); lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } Program.HideObject(opaque_ref); var action = new EjectHostFromPoolAction(pool, host); action.Completed += delegate { if (action.Succeeded) { ThreadPool.QueueUserWorkItem(WaitForReboot, connection); } else { Program.ShowObject(opaque_ref); MainWindowCommandInterface.RemoveConnection(connection); } }; actions.Add(action); } RunMultipleActions(actions, Messages.REMOVING_SERVERS_FROM_POOL, Messages.POOLCREATE_REMOVING, Messages.POOLCREATE_REMOVED, true); }
private TreeNode AddHostNode(TreeNode parent, int index, XenConnection connection, Host host) { bool expand; bool live; TreeNode node = this.AddHostNode(parent, index, connection, host, out expand, out live); //node.ForeColor = SystemColors.GrayText; node.Checked = true; return(node); }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { log.Info("XenServer Health Check Service start to refresh uploading tasks"); //We need to check if CIS can be accessed in current enviroment List <ServerInfo> servers = ServerListHelper.instance.GetServerList(); foreach (ServerInfo server in servers) { if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted)) { continue; } XenConnection connectionInfo = new XenConnection(); connectionInfo.Hostname = server.HostName; connectionInfo.Username = server.UserName; connectionInfo.Password = server.Password; log.InfoFormat("Check server {0} with user {1}", connectionInfo.Hostname, connectionInfo.Username); Session session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; try { session.login_with_password(server.UserName, server.Password); connectionInfo.LoadCache(session); if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session)) { // Create a task to collect server status report and upload to CIS server log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname); XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo); Action uploadAction = delegate() { upload.runUpload(cts.Token); }; System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction); task.Start(); server.task = task; ServerListHelper.instance.UpdateServerInfo(server); } session.logout(); session = null; } catch (Exception exn) { if (session != null) { session.logout(); } log.Error(exn, exn); } } }
public void TestSingleParentNodeGetsSelectedWhenMultipleNodesDisappear() { IXenConnection con1 = new XenConnection(); IXenConnection con2 = new XenConnection(); IXenConnection con3 = new XenConnection(); VirtualTreeNode root = new VirtualTreeNode("root"); root.Nodes.Add(new VirtualTreeNode("1") { Tag = new Folder(null, "1") { Connection = con1 } }); root.Nodes.Add(new VirtualTreeNode("2") { Tag = new Folder(null, "2") { Connection = con2 } }); root.Nodes.Add(new VirtualTreeNode("3") { Tag = new Folder(null, "3") { Connection = con3 } }); _tv.BeginUpdate(); _tv.UpdateRootNodes(new [] { root }); _tv.EndUpdate(); _tv.SelectedNodes.SetContents(new [] { root.Nodes[0], root.Nodes[1] }); root = new VirtualTreeNode("root"); root.Nodes.Add(new VirtualTreeNode("3") { Tag = new Folder(null, "3") { Connection = con3 } }); _tv.BeginUpdate(); _tv.UpdateRootNodes(new [] { root }); _tv.EndUpdate(); Assert.AreEqual(1, _tv.SelectedNodes.Count, "Nodes didn't stay selected"); Assert.AreEqual("root", _tv.SelectedNode.Text, "Nodes didn't stay selected"); }
private void SettingValue() { if (this.DefaultStorageDataGridView.CurrentRow != null) { this._choice_sr_uuid = this.DefaultStorageDataGridView.CurrentRow.Tag.ToString(); this._choice_sr_ip = this.DefaultStorageDataGridView.CurrentRow.Cells[1].Value.ToString().TrimEnd().TrimStart(); this._choice_sr_name = this.DefaultStorageDataGridView.CurrentRow.Cells[0].Value.ToString(); this._choice_sr_ip_name = this.DefaultStorageDataGridView.CurrentRow.Cells[1].Value.ToString() + ":" + this.DefaultStorageDataGridView.CurrentRow.Cells[2].Value.ToString(); this._choice_sr_free_space = this.DefaultStorageDataGridView.CurrentRow.Cells[3].Value.ToString(); this.selected_xenConnection = this.DefaultStorageDataGridView.CurrentRow.Cells[0].Tag as XenConnection; this.selected_host = this.DefaultStorageDataGridView.CurrentRow.Cells[1].Tag as Host; } }
protected IXenConnection LoadDB(string name, string username) { string fileName = TestResource(name); IXenConnection connection = new XenConnection(fileName, name); connection.Username = username; connection.Password = ""; lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } XenConnectionUI.BeginConnect(connection, false, null, false); return(connection); }
public XenModelObjectPropertyQuery(XmlNode node) : base(node) { XmlAttribute uuid_node = node.Attributes["uuid"]; if (uuid_node == null) { // Just for backwards compat. query = XenConnection.FindByRef(new XenRef <T>(Helpers.GetXmlAttribute(node, "query"))); } else { query = XenConnection.FindByUUIDXenObject <T>(uuid_node.Value); } equals = SearchMarshalling.ParseBool(Helpers.GetXmlAttribute(node, "equals")); }
private void DefualtStorageDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e) { if (this.DefaultStorageDataGridView.CurrentRow != null) { int _rowIndex = e.RowIndex; this._choice_sr_uuid = this.DefaultStorageDataGridView.Rows[_rowIndex].Tag.ToString(); this._choice_sr_ip = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[1].Value.ToString().TrimEnd().TrimStart(); this._choice_sr_name = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[0].Value.ToString(); this._choice_sr_ip_name = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[1].Value.ToString() + ":" + this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[2].Value.ToString(); this._choice_sr_free_space = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[3].Value.ToString(); this.selected_xenConnection = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[0].Tag as XenConnection; this.selected_host = this.DefaultStorageDataGridView.Rows[_rowIndex].Cells[1].Tag as Host; this.InitNetworkListBox(); this.InitCredentials(); base.OnPageUpdated(); } }
private IXenConnection LoadDB(string name, string username) { var connection = new XenConnection { Username = username, Password = "", Hostname = TestResource(name), FriendlyName = name, Port = 443, SaveDisconnected = true }; lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } XenConnectionUI.BeginConnect(connection, false, null, false); return(connection); }
private static void AddConnection(IXenConnection connection) { if (ConnectionsManager.XenConnectionsContains(connection)) { return; } XenConnection conn = connection as XenConnection; conn.LastConnectionFullName = string.IsNullOrEmpty(connection.FriendlyName) ? connection.Hostname : string.Format("{0} ({1})", connection.FriendlyName, connection.Hostname); lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } }
/// <summary> /// Tries to restore the session list using the given password hash as /// the key. Returns true if successful, false otherwise (usu. due to /// a decryption failure, in turn due to a wrong password). /// </summary> /// <param name="passHash"></param> /// <param name="useOriginalList"></param> /// <returns></returns> private static bool RestoreSessionWithPassword(byte[] passHash, bool useOriginalList) { string[] encServerList; if (useOriginalList) { // if we are resuming without a password or have a valid password use Settings.ServerList encServerList = Properties.Settings.Default.ServerList ?? new string[0]; } else { // user has cancelled, use the ServerAddressList (no usernames or passwords) encServerList = Properties.Settings.Default.ServerAddressList ?? new string[0]; } string[] decryptedList = new string[encServerList.Length]; if (!Properties.Settings.Default.RequirePass || !useOriginalList) { int idx = 0; try { foreach (string encEntry in encServerList) { decryptedList[idx] = EncryptionUtils.Unprotect(encEntry); idx++; } } catch (Exception exp) { log.Warn("Could not unprotect session information", exp); return(false); } } else { int idx = 0; try { foreach (string encEntry in encServerList) { decryptedList[idx] = EncryptionUtils.DecryptString(encEntry, passHash); idx++; } } catch (Exception exp) { log.Warn("Could not decrypt session information", exp); // Problem decrypting -> wrong password entered... return(false); } } // Validate the decrypted entries - the session entries may // have been decrypted to nonsense... foreach (string entry in decryptedList) { string[] entryComps = entry.Split(SEPARATOR); if (entryComps.Length < 3 || entryComps.Length > 7) { log.Warn("Did not decrypt session list to a valid entry..."); return(false); } } foreach (string entry in decryptedList) { // $VNC$, VM UUID, unused, password // username, hostname, port, password // username, hostname, port, password, connected // username, hostname, port, password, connected, friendly name // username, hostname, port, password, connected, friendly name, pool members // If the user cancels the restore dialog, we use the ServerAddressList instead: // hostname, port, friendly name string[] entryComps = entry.Split(SEPARATOR); int port; if (!int.TryParse(entryComps[2], out port)) { port = ConnectionsManager.DEFAULT_XEN_PORT; } if (entryComps[0] == VNC_INDICATOR) { string vm_uuid = entryComps[1]; VNCPasswords[vm_uuid] = entryComps[3]; } else if (entryComps.Length == 3) { if (!int.TryParse(entryComps[1], out port)) { port = ConnectionsManager.DEFAULT_XEN_PORT; } IXenConnection connection = new XenConnection(); connection.Hostname = entryComps[0]; connection.Port = port; connection.Password = null; connection.SaveDisconnected = true; connection.FriendlyName = entryComps[2] != "" ? entryComps[2] : entryComps[0]; AddConnection(connection); } else { IXenConnection connection = new XenConnection(); connection.Username = entryComps[0]; connection.Hostname = entryComps[1]; connection.Port = port; // If password is NO_PASSWORD, this indicates we didn't save a password for this connection if (entryComps[3] == NO_PASSWORD) { connection.Password = null; connection.ExpectPasswordIsCorrect = false; } else { connection.Password = entryComps[3]; } connection.SaveDisconnected = entryComps.Length > 4 && entryComps[4] == DISCONNECTED; connection.FriendlyName = entryComps.Length > 5 ? entryComps[5] : entryComps[1]; // We save a comma-separated list of hostnames of each of the slaves. // This enables us to connect to a former slave in the event of master failover while the GUI isn't running. if (entryComps.Length == 7 && entryComps[6] != "") { connection.PoolMembers = new List <string>(entryComps[6].Split(new char[] { ',' })); } else { connection.PoolMembers = new List <string>(new string[] { connection.Hostname }); } AddConnection(connection); } } return(true); }
protected override void ExecuteCore(SelectedItemCollection selection) { List<AsyncAction> actions = new List<AsyncAction>(); foreach (Host host in selection.AsXenObjects<Host>()) { string opaque_ref = host.opaque_ref; Pool pool = Helpers.GetPool(host.Connection); if (selection.Count == 1 && pool.master == host.opaque_ref) { // Trying to remove the master from a pool. new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, Messages.MESSAGEBOX_POOL_MASTER_REMOVE, Messages.XENCENTER)).ShowDialog(MainWindowCommandInterface.Form); return; } // Optimistically, add the ejected host as a standalone host (but don't connect to it yet) IXenConnection connection = new XenConnection(); connection.Hostname = host.address; connection.Username = host.Connection.Username; connection.Password = host.Connection.Password; connection.FriendlyName = host.Name; lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } Program.HideObject(opaque_ref); var action = new EjectHostFromPoolAction(pool, host); action.Completed += delegate { if (action.Succeeded) { ThreadPool.QueueUserWorkItem(WaitForReboot, connection); } else { Program.ShowObject(opaque_ref); MainWindowCommandInterface.RemoveConnection(connection); } }; actions.Add(action); } RunMultipleActions(actions, Messages.REMOVING_SERVERS_FROM_POOL, Messages.POOLCREATE_REMOVING, Messages.POOLCREATE_REMOVED, true); }
private static void ShowConnectingDialogError(Form owner, IXenConnection connection, Exception error) { if (error is ExpressRestriction e) { Program.Invoke(Program.MainWindow, delegate() { new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner); }); return; } if (error is Failure f) { if (f.ErrorDescription[0] == Failure.HOST_IS_SLAVE) { string oldHost = connection.Name; string poolMasterName = f.ErrorDescription[1]; string pool_name = XenConnection.ConnectedElsewhere(poolMasterName); if (pool_name != null) { if (!Program.RunInAutomatedTestMode) { if (pool_name == oldHost) { using (var dlg = new InformationDialog(string.Format(Messages.OLD_CONNECTION_ALREADY_CONNECTED, pool_name)) { WindowTitle = Messages.ADD_NEW_CONNECT_TO }) { dlg.ShowDialog(owner); } } else { using (var dlg = new InformationDialog(string.Format(Messages.SLAVE_ALREADY_CONNECTED, oldHost, pool_name)) { WindowTitle = Messages.ADD_NEW_CONNECT_TO }) { dlg.ShowDialog(owner); } } } } else { DialogResult dialogResult; using (var dlg = new WarningDialog(string.Format(Messages.SLAVE_CONNECTION_ERROR, oldHost, poolMasterName), ThreeButtonDialog.ButtonYes, ThreeButtonDialog.ButtonNo) { WindowTitle = Messages.CONNECT_TO_SERVER }) { dialogResult = dlg.ShowDialog(owner); } if (DialogResult.Yes == dialogResult) { ((XenConnection)connection).Hostname = poolMasterName; BeginConnect(connection, true, owner, false); } } } else if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { AddError(owner, connection, Messages.ERROR_NO_PERMISSION, Messages.SOLUTION_NO_PERMISSION); } else if (f.ErrorDescription[0] == XenAPI.Failure.SESSION_AUTHENTICATION_FAILED) { AddError(owner, connection, Messages.ERROR_AUTHENTICATION, Messages.SOLUTION_AUTHENTICATION); } else if (f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING) { AddError(owner, connection, Messages.ERROR_HOST_STILL_BOOTING, Messages.SOLUTION_HOST_STILL_BOOTING); } else { AddError(owner, connection, string.IsNullOrEmpty(f.Message) ? Messages.ERROR_UNKNOWN : f.Message, string.Empty); } } else if (error is WebException w) { if (((XenConnection)connection).SuppressErrors) { return; } var solutionCheckXenServer = Properties.Settings.Default.ProxySetting != (int)HTTPHelper.ProxyStyle.DirectConnection ? Messages.SOLUTION_CHECK_XENSERVER_WITH_PROXY : Messages.SOLUTION_CHECK_XENSERVER; switch (w.Status) { case WebExceptionStatus.ConnectionClosed: AddError(owner, connection, Messages.CONNECTION_CLOSED_BY_SERVER, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname)); break; case WebExceptionStatus.ConnectFailure: AddError(owner, connection, Messages.CONNECTION_REFUSED, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname)); break; case WebExceptionStatus.ProtocolError: if (w.Message != null && w.Message.Contains("(404)")) { AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname)); } else if (w.Message != null && w.Message.Contains("(407)")) { string proxyAddress = Properties.Settings.Default.ProxyAddress; AddError(owner, connection, string.Format(Messages.ERROR_PROXY_AUTHENTICATION, proxyAddress), string.Format(Messages.SOLUTION_CHECK_PROXY, proxyAddress)); } else { AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN); } break; case WebExceptionStatus.NameResolutionFailure: AddError(owner, connection, string.Format(Messages.ERROR_NOT_FOUND, ((XenConnection)connection).Hostname), Messages.SOLUTION_NOT_FOUND); break; case WebExceptionStatus.ReceiveFailure: case WebExceptionStatus.SendFailure: AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname)); break; case WebExceptionStatus.SecureChannelFailure: AddError(owner, connection, string.Format(Messages.ERROR_SECURE_CHANNEL_FAILURE, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN); break; default: AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN); break; } } else if (error is UriFormatException) { AddError(owner, connection, string.Format(Messages.ERROR_INVALID_URI, connection.Name), Messages.SOLUTION_NOT_FOUND); } else if (error is FileNotFoundException) { // If you're using the DbProxy AddError(owner, connection, string.Format(string.Format(Messages.ERROR_FILE_NOT_FOUND, ((XenConnection)connection).Hostname), connection.Name), Messages.SOLUTION_UNKNOWN); } else if (error is ConnectionExists c) { ConnectionsManager.ClearCacheAndRemoveConnection(connection); if (!Program.RunInAutomatedTestMode) { using (var dlg = new InformationDialog(c.GetDialogMessage(connection))) dlg.ShowDialog(owner); } } else if (error is ArgumentException) { // This happens if the server API is incompatible with our bindings. This should // never happen in production, but will happen during development if a field // changes type, for example. AddError(owner, connection, Messages.SERVER_API_INCOMPATIBLE, Messages.SOLUTION_UNKNOWN); } else if (error is ServerNotSupported) { // Server version is too old for this version of XenCenter AddError(owner, connection, string.Format(Messages.SERVER_TOO_OLD, BrandManager.ProductVersion70), Messages.SERVER_TOO_OLD_SOLUTION); } else { if (((XenConnection)connection).SuppressErrors) { return; } AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN); } }
public void TestSingleParentNodeGetsSelectedWhenMultipleNodesDisappear() { IXenConnection con1 = new XenConnection(); IXenConnection con2 = new XenConnection(); IXenConnection con3 = new XenConnection(); VirtualTreeNode root = new VirtualTreeNode("root"); root.Nodes.Add(new VirtualTreeNode("1") { Tag = new Folder(null, "1") { Connection = con1 } }); root.Nodes.Add(new VirtualTreeNode("2") { Tag = new Folder(null, "2") { Connection = con2 } }); root.Nodes.Add(new VirtualTreeNode("3") { Tag = new Folder(null, "3") { Connection = con3 } }); _tv.BeginUpdate(); _tv.UpdateRootNodes(new VirtualTreeNode[] { root }); _tv.EndUpdate(); _tv.SelectedNodes.SetContents(new VirtualTreeNode[] { root.Nodes[0], root.Nodes[1] }); root = new VirtualTreeNode("root"); root.Nodes.Add(new VirtualTreeNode("3") { Tag = new Folder(null, "3") { Connection = con3 } }); _tv.BeginUpdate(); _tv.UpdateRootNodes(new VirtualTreeNode[] { root }); _tv.EndUpdate(); Assert.AreEqual(1, _tv.SelectedNodes.Count, "Nodes didn't stay selected"); Assert.AreEqual("root", _tv.SelectedNode.Text, "Nodes didn't stay selected"); }
private void buttonAddNewServer_Click(object sender, EventArgs e) { IXenConnection newConnection = new XenConnection(); newConnections.Add(newConnection); new AddServerTask(this, newConnection, null).Start(); }
private static void WriteXML(string destdir, string token, string error) { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, null)); XmlElement root = doc.CreateElement(RootElement, NamespaceURI); root.SetAttribute("version", "1.0"); doc.AppendChild(root); if (error != null) { XmlElement error_node = doc.CreateElement("error", NamespaceURI); root.AppendChild(error_node); error_node.SetAttribute("code", error); } else { if (token != null) { XmlElement token_node = doc.CreateElement(TokenElement, NamespaceURI); root.AppendChild(token_node); token_node.AppendChild(doc.CreateTextNode(token)); } foreach (IXenConnection conn in ConnectionsManager.XenConnectionsCopy) { XenConnection connection = conn as XenConnection; XmlElement pool_node = doc.CreateElement("pool", NamespaceURI); root.AppendChild(pool_node); pool_node.SetAttribute("name_label", conn.FriendlyName); pool_node.SetAttribute("password", conn.Password); pool_node.SetAttribute("is_connected", conn.SaveDisconnected ? "false" : "true"); lock (connection.PoolMembersLock) { pool_node.AppendChild(ServerNode(doc, conn.Hostname, conn.Port, true)); foreach (string member in conn.PoolMembers) { if (member != conn.Hostname) { pool_node.AppendChild(ServerNode(doc, member, conn.Port, false)); } } } } } XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; settings.Indent = true; settings.Encoding = Encoding.UTF8; string dest = Path.Combine(destdir, ResultFilename); XmlWriter writer = XmlWriter.Create(dest, settings); try { doc.WriteContentTo(writer); } finally { writer.Close(); } }
protected IXenConnection LoadDB(string name, string username) { string fileName = TestResource(name); IXenConnection connection = new XenConnection(fileName, name); connection.Username = username; connection.Password = ""; lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(connection); } XenConnectionUI.BeginConnect(connection, false, null, false); return connection; }
public void InitReplicationViewData() { BackupRestoreConfig.BrSchedule schedule = (BackupRestoreConfig.BrSchedule)HalsignUtil.JsonToObject(other_config["halsign_rep_rules"], typeof(BackupRestoreConfig.BrSchedule)); BackupRestoreConfig.Job job = (BackupRestoreConfig.Job)HalsignUtil.JsonToObject(other_config["halsign_br_job_r"], typeof(BackupRestoreConfig.Job)); this.Text = schedule.jobName + this.Text; string[] details = schedule.details.Split('|'); VMNameDetailLabel.Text = vm_name; if (job.request.StartsWith(BackupRestoreConfig.REPLICATION_ONCE)) { JobScheduleTypeDetailLabel.Text = Messages.REPLICATION_ONCE; } else if (job.request.StartsWith(BackupRestoreConfig.REPLICATION_DAILY)) { JobScheduleTypeDetailLabel.Text = Messages.REPLICATION_DAILY; RecurDetailLabel.Text = schedule.recur + Messages.BACKUP_RECUR_TEXT_DAYS; } else if (job.request.StartsWith(BackupRestoreConfig.REPLICATION_WEEKLY)) { JobScheduleTypeDetailLabel.Text = Messages.REPLICATION_WEEKLY; List <int> WeeklyDays = schedule.weeklyDays; WeeklyDays.Sort(); string WeeklyDayStr = ""; if (WeeklyDays != null && WeeklyDays.Count > 0) { foreach (var weeklyDay in WeeklyDays) { switch (weeklyDay) { case 0: WeeklyDayStr += Messages.SUNDAY + ","; break; case 1: WeeklyDayStr += Messages.MONDAY + ","; break; case 2: WeeklyDayStr += Messages.TUESDAY + ","; break; case 3: WeeklyDayStr += Messages.WEDNESDAY + ","; break; case 4: WeeklyDayStr += Messages.THURSDAY + ","; break; case 5: WeeklyDayStr += Messages.FRIDAY + ","; break; case 6: WeeklyDayStr += Messages.SATURDAY + ","; break; } } } WeeklyDaysDetailLabel.Text += WeeklyDayStr.Substring(0, WeeklyDayStr.Length - 1); RecurDetailLabel.Text = schedule.recur + Messages.BACKUP_RECUR_TEXT_WEEKS; } else if (job.request.StartsWith(BackupRestoreConfig.REPLICATION_CIRCLE)) { JobScheduleTypeDetailLabel.Text = Messages.REPLICATION_CIRCLE; RecurDetailLabel.Text = schedule.recur + Messages.BACKUP_RECUR_TEXT_HOURS; } JobNameDetailLable.Text = schedule.jobName; StartDateDetailLabel.Text = schedule.scheduleDate; StartTimeDetailLabel.Text = schedule.scheduleTime; AppendDetailLabel.Text = details[3]; DestServerDetailLabel.Text = details[0]; DestSRDetailLabel.Text = details[4]; NetworkDetailLabel.Text = details[7]; string hostname = details[0]; //int port = 80; // default string user = details[1]; string password = details[2]; Session session = null; try { XenConnection XenConnection = new XenConnection(hostname, ""); session = SessionFactory.CreateSession(connection, hostname, 443); session.login_with_password(user, password, API_Version.LATEST); /*XenRef<SR> sr = SR.get_by_uuid(session, details[4]); * DestSRDetailLabel.Text = SR.get_name_label(session, sr); * XenRef<XenAPI.Network> network = XenAPI.Network.get_by_uuid(session, details[7]); * NetworkDetailLabel.Text = XenAPI.Network.get_name_label(session, network).Replace("Pool-wide network associated with eth", Messages.NETWORK); */ setSrNetwork(session, details); }catch (Failure exn) { if ("HOST_IS_SLAVE".Equals(exn.ErrorDescription[0])) { session = SessionFactory.CreateSession(connection, exn.ErrorDescription[1], 443); session.login_with_password(user, password, API_Version.LATEST); setSrNetwork(session, details); } } /*catch (Failure f) * { * if (f.ErrorDescription.Count > 0) * throw new CancelledException(); * }*/ finally { if (session != null) { session.logout(); } } OptionDetailLabel.Text = ""; }
internal static void ShowConnectingDialogError_(Form owner, IXenConnection connection, Exception error) { if (error is ExpressRestriction) { ExpressRestriction e = (ExpressRestriction)error; Program.Invoke(Program.MainWindow, delegate() { new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner); }); return; } if (error is Failure) { Failure f = (Failure)error; if (f.ErrorDescription[0] == Failure.HOST_IS_SLAVE) { string oldHost = connection.Name; string poolMasterName = f.ErrorDescription[1]; string pool_name = XenConnection.ConnectedElsewhere(poolMasterName); if (pool_name != null) { if (!Program.RunInAutomatedTestMode) { if (pool_name == oldHost) { new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Information, string.Format(Messages.OLD_CONNECTION_ALREADY_CONNECTED, pool_name), Messages.ADD_NEW_CONNECT_TO)).ShowDialog(owner); } else { new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Information, string.Format(Messages.SLAVE_ALREADY_CONNECTED, oldHost, pool_name), Messages.ADD_NEW_CONNECT_TO)).ShowDialog(owner); } } } else { if (DialogResult.Yes == new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Warning, String.Format(Messages.SLAVE_CONNECTION_ERROR, oldHost, poolMasterName), Messages.CONNECT_TO_SERVER), ThreeButtonDialog.ButtonYes, ThreeButtonDialog.ButtonNo).ShowDialog(owner)) { ((XenConnection)connection).Hostname = poolMasterName; BeginConnect(connection, true, owner, false); } } } else if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { AddError(owner, connection, Messages.ERROR_NO_PERMISSION, Messages.SOLUTION_NO_PERMISSION); } else if (f.ErrorDescription[0] == XenAPI.Failure.SESSION_AUTHENTICATION_FAILED) { AddError(owner, connection, Messages.ERROR_AUTHENTICATION, Messages.SOLUTION_AUTHENTICATION); } else if (f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING) { AddError(owner, connection, Messages.ERROR_HOST_STILL_BOOTING, Messages.SOLUTION_HOST_STILL_BOOTING); } else { AddError(owner, connection, string.IsNullOrEmpty(f.Message) ? Messages.ERROR_UNKNOWN : f.Message, string.Empty); } } else if (error is WebException) { if (((XenConnection)connection).SupressErrors) { return; } WebException w = (WebException)error; switch (w.Status) { case WebExceptionStatus.ConnectionClosed: AddError(owner, connection, Messages.CONNECTION_CLOSED_BY_SERVER, string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname)); break; case WebExceptionStatus.ConnectFailure: AddError(owner, connection, Messages.CONNECTION_REFUSED, string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname)); break; case WebExceptionStatus.ProtocolError: if (w.Message != null && w.Message.Contains("(404)")) { AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname)); } else { AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN); } break; case WebExceptionStatus.NameResolutionFailure: AddError(owner, connection, string.Format(Messages.ERROR_NOT_FOUND, ((XenConnection)connection).Hostname), Messages.SOLUTION_NOT_FOUND); break; case WebExceptionStatus.ReceiveFailure: case WebExceptionStatus.SendFailure: AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname)); break; default: AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN); break; } } else if (error is UriFormatException) { AddError(owner, connection, string.Format(Messages.ERROR_INVALID_URI, connection.Name), Messages.SOLUTION_NOT_FOUND); } else if (error is FileNotFoundException) { // If you're using the DbProxy AddError(owner, connection, string.Format(string.Format(Messages.ERROR_FILE_NOT_FOUND, ((XenConnection)connection).Hostname), connection.Name), Messages.SOLUTION_UNKNOWN); } else if (error is ConnectionExists) { ConnectionsManager.ClearCacheAndRemoveConnection(connection); if (!Program.RunInAutomatedTestMode) { ConnectionExists c = error as ConnectionExists; new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Information, c.GetDialogMessage(connection), Messages.XENCENTER)).ShowDialog(owner); } } else if (error is ArgumentException) { // This happens if the server API is incompatible with our bindings. This should // never happen in production, but will happen during development if a field // changes type, for example. AddError(owner, connection, Messages.SERVER_API_INCOMPATIBLE, Messages.SOLUTION_UNKNOWN); } else if (error is ServerNotSupported) { // Server version is too old for this version of XenCenter AddError(owner, connection, Messages.SERVER_TOO_OLD, Messages.SERVER_TOO_OLD_SOLUTION); } else { if (((XenConnection)connection).SupressErrors) { return; } AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN); } }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { log.Info("XenServer Health Check Service start to refresh uploading tasks"); //We need to check if CIS can be accessed in current enviroment List <ServerInfo> servers = ServerListHelper.instance.GetServerList(); foreach (ServerInfo server in servers) { if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted)) { continue; } bool needReconnect = false; log.InfoFormat("Check server {0} with user {1}", server.HostName, server.UserName); Session session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; try { session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); } catch (Exception exn) { if (exn is Failure && ((Failure)exn).ErrorDescription[0] == Failure.HOST_IS_SLAVE) { string masterName = ((Failure)exn).ErrorDescription[1]; if (ServerListHelper.instance.UpdateServerCredential(server, masterName)) { log.InfoFormat("Refresh credential to master {0} need refresh connection", masterName); server.HostName = masterName; needReconnect = true; } else { log.InfoFormat("Remove credential since it is the slave of master {0}", masterName); if (session != null) { session.logout(); } log.Error(exn, exn); continue; } } else { if (session != null) { session.logout(); } log.Error(exn, exn); continue; } } try { if (needReconnect) { if (session != null) { session.logout(); } log.InfoFormat("Reconnect to master {0}", server.HostName); session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); } XenConnection connectionInfo = new XenConnection(); connectionInfo.Hostname = server.HostName; connectionInfo.Username = server.UserName; connectionInfo.Password = server.Password; connectionInfo.LoadCache(session); if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session)) { // Create a task to collect server status report and upload to CIS server log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname); XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo); Action uploadAction = delegate() { upload.runUpload(cts.Token); }; System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction); task.Start(); server.task = task; ServerListHelper.instance.UpdateServerInfo(server); } session.logout(); session = null; } catch (Exception exn) { if (session != null) { session.logout(); } log.Error(exn, exn); } } }
/// <param name="connection">May be null, in which case a new connection will be created</param> protected void ConnectToServer(IXenConnection conn, string hostname, int port, string username, string password, string version) { if (conn == null) { XenConnection connection = new XenConnection(); connection.CachePopulated += conn_CachePopulated; connection.fromDialog = true; conn = connection; } else if (!_changedPass) { conn.EndConnect(); // in case we're already connected } conn.Hostname = hostname; conn.Port = port; conn.Username = username; conn.Password = password; conn.ExpectPasswordIsCorrect = false; conn.Version = version; if (!_changedPass) XenConnectionUI.BeginConnect(conn, true, Owner, false); }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { log.Info("XenServer Health Check Service start to refresh uploading tasks"); //We need to check if CIS can be accessed in current enviroment List<ServerInfo> servers = ServerListHelper.instance.GetServerList(); foreach (ServerInfo server in servers) { if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted)) { continue; } bool needReconnect = false; log.InfoFormat("Check server {0} with user {1}", server.HostName, server.UserName); Session session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; try { session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); } catch (Exception exn) { if (exn is Failure && ((Failure)exn).ErrorDescription[0] == Failure.HOST_IS_SLAVE) { string masterName = ((Failure)exn).ErrorDescription[1]; if (ServerListHelper.instance.UpdateServerCredential(server, masterName)) { log.InfoFormat("Refresh credential to master {0} need refresh connection", masterName); server.HostName = masterName; needReconnect = true; } else { log.InfoFormat("Remove credential since it is the slave of master {0}", masterName); if (session != null) session.logout(); log.Error(exn, exn); continue; } } else { if (session != null) session.logout(); log.Error(exn, exn); continue; } } try { if (needReconnect) { if (session != null) session.logout(); log.InfoFormat("Reconnect to master {0}", server.HostName); session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; session.login_with_password(server.UserName, server.Password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); } XenConnection connectionInfo = new XenConnection(); connectionInfo.Hostname = server.HostName; connectionInfo.Username = server.UserName; connectionInfo.Password = server.Password; connectionInfo.LoadCache(session); if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session)) { // Create a task to collect server status report and upload to CIS server log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname); XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo); Action uploadAction = delegate() { upload.runUpload(cts.Token); }; System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction); task.Start(); server.task = task; ServerListHelper.instance.UpdateServerInfo(server); } session.logout(); session = null; } catch (Exception exn) { if (session != null) session.logout(); log.Error(exn, exn); } } }
/// <summary> /// Tries to restore the session list using the given password hash as /// the key. Returns true if successful, false otherwise (usu. due to /// a decryption failure, in turn due to a wrong password). /// </summary> /// <param name="passHash"></param> /// <param name="useOriginalList"></param> /// <returns></returns> private static bool RestoreSessionWithPassword(byte[] passHash, bool useOriginalList) { string[] encServerList; if (useOriginalList) { // if we are resuming without a password or have a valid password use Settings.ServerList encServerList = Properties.Settings.Default.ServerList ?? new string[0]; } else { // user has cancelled, use the ServerAddressList (no usernames or passwords) encServerList = Properties.Settings.Default.ServerAddressList ?? new string[0]; } string[] decryptedList = new string[encServerList.Length]; if (!Properties.Settings.Default.RequirePass || !useOriginalList) { int idx = 0; try { foreach (string encEntry in encServerList) { decryptedList[idx] = EncryptionUtils.Unprotect(encEntry); idx++; } } catch (Exception exp) { log.Warn("Could not unprotect session information", exp); return false; } } else { int idx = 0; try { foreach (string encEntry in encServerList) { decryptedList[idx] = EncryptionUtils.DecryptString(encEntry, passHash); idx++; } } catch (Exception exp) { log.Warn("Could not decrypt session information", exp); // Problem decrypting -> wrong password entered... return false; } } // Validate the decrypted entries - the session entries may // have been decrypted to nonsense... foreach (string entry in decryptedList) { string[] entryComps = entry.Split(SEPARATOR); if (entryComps.Length < 3 || entryComps.Length > 7) { log.Warn("Did not decrypt session list to a valid entry..."); return false; } } foreach (string entry in decryptedList) { // $VNC$, VM UUID, unused, password // username, hostname, port, password // username, hostname, port, password, connected // username, hostname, port, password, connected, friendly name // username, hostname, port, password, connected, friendly name, pool members // If the user cancels the restore dialog, we use the ServerAddressList instead: // hostname, port, friendly name string[] entryComps = entry.Split(SEPARATOR); int port; if (!int.TryParse(entryComps[2], out port)) { port = ConnectionsManager.DEFAULT_XEN_PORT; } if (entryComps[0] == VNC_INDICATOR) { string vm_uuid = entryComps[1]; VNCPasswords[vm_uuid] = entryComps[3]; } else if (entryComps.Length == 3) { if (!int.TryParse(entryComps[1], out port)) { port = ConnectionsManager.DEFAULT_XEN_PORT; } IXenConnection connection = new XenConnection(); connection.Hostname = entryComps[0]; connection.Port = port; connection.Password = null; connection.SaveDisconnected = true; connection.FriendlyName = entryComps[2] != "" ? entryComps[2] : entryComps[0]; AddConnection(connection); } else { IXenConnection connection = new XenConnection(); connection.Username = entryComps[0]; connection.Hostname = entryComps[1]; connection.Port = port; // If password is NO_PASSWORD, this indicates we didn't save a password for this connection if (entryComps[3] == NO_PASSWORD) { connection.Password = null; connection.ExpectPasswordIsCorrect = false; } else { connection.Password = entryComps[3]; } connection.SaveDisconnected = entryComps.Length > 4 && entryComps[4] == DISCONNECTED; connection.FriendlyName = entryComps.Length > 5 ? entryComps[5] : entryComps[1]; // We save a comma-separated list of hostnames of each of the slaves. // This enables us to connect to a former slave in the event of master failover while the GUI isn't running. if (entryComps.Length == 7 && entryComps[6] != "") { connection.PoolMembers = new List<string>(entryComps[6].Split(new char[] { ',' })); } else { connection.PoolMembers = new List<string>(new string[] { connection.Hostname }); } AddConnection(connection); } } return true; }
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args) { log.Info("XenServer Health Check Service start to refresh uploading tasks"); //We need to check if CIS can be accessed in current enviroment List<ServerInfo> servers = ServerListHelper.instance.GetServerList(); foreach (ServerInfo server in servers) { if (server.task != null && (!server.task.IsCompleted || !server.task.IsCanceled || !server.task.IsFaulted)) { continue; } XenConnection connectionInfo = new XenConnection(); connectionInfo.Hostname = server.HostName; connectionInfo.Username = server.UserName; connectionInfo.Password = server.Password; log.InfoFormat("Check server {0} with user {1}", connectionInfo.Hostname, connectionInfo.Username); Session session = new Session(server.HostName, 80); session.APIVersion = API_Version.LATEST; try { session.login_with_password(server.UserName, server.Password); connectionInfo.LoadCache(session); if (RequestUploadTask.Request(connectionInfo, session) || RequestUploadTask.OnDemandRequest(connectionInfo, session)) { // Create a task to collect server status report and upload to CIS server log.InfoFormat("Start to upload server status report for XenServer {0}", connectionInfo.Hostname); XenServerHealthCheckBundleUpload upload = new XenServerHealthCheckBundleUpload(connectionInfo); Action uploadAction = delegate() { upload.runUpload(cts.Token); }; System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(uploadAction); task.Start(); server.task = task; ServerListHelper.instance.UpdateServerInfo(server); } session.logout(); session = null; } catch (Exception exn) { if (session != null) session.logout(); log.Error(exn, exn); } } }
private void CreateNewConnection(string dbFileName, string username, string password) { string fileName = TestResource(dbFileName); Assert.True(File.Exists(fileName), String.Format("Provided filename does not exist: '{0}'. " + "If this is a new file, maybe the 'Copy To Ouput Directory' property has not been set", fileName)); XenAdminConfigManager.Provider = new TestXenAdminConfigProvider(); IXenConnection connection = new XenConnection(fileName, dbFileName); ServicePointManager.DefaultConnectionLimit = 20; ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate; Session session = connection.Connect(username, password); Assert.NotNull(session); connection.LoadCache(session); Assert.True(connection.CacheIsPopulated); lock (ConnectionListLock) { if (connections.ContainsKey(dbFileName)) connections.Remove(dbFileName); connections.Add(dbFileName,connection); } }