/// <summary> /// Displays a dialog informing the user they need a different role to complete the task, and offers the chance to switch user. Optionally logs /// out the elevated session. If successful exposes the elevated session, password and username as fields. /// </summary> /// <param name="connection">The current server connection with the role information</param> /// <param name="session">The session on which we have been denied access</param> /// <param name="authorizedRoles">A list of roles that are able to complete the task</param> /// <param name="actionTitle">A description of the current action, if null or empty will not be displayed</param> public RoleElevationDialog(IXenConnection connection, Session session, List<Role> authorizedRoles, string actionTitle) { InitializeComponent(); Image icon = SystemIcons.Exclamation.ToBitmap(); pictureBox1.Image = icon; pictureBox1.Width = icon.Width; pictureBox1.Height = icon.Height; this.connection = connection; UserDetails ud = session.CurrentUserDetails; labelCurrentUserValue.Text = ud.UserDisplayName ?? ud.UserName ?? Messages.UNKNOWN_AD_USER; labelCurrentRoleValue.Text = Role.FriendlyCSVRoleList(session.Roles); authorizedRoles.Sort((r1, r2) => r2.CompareTo(r1)); labelRequiredRoleValue.Text = Role.FriendlyCSVRoleList(authorizedRoles); labelServerValue.Text = Helpers.GetName(connection); labelServer.Text = Helpers.IsPool(connection) ? Messages.POOL_COLON : Messages.SERVER_COLON; originalUsername = session.Connection.Username; originalPassword = session.Connection.Password; if (string.IsNullOrEmpty(actionTitle)) { labelCurrentAction.Visible = false; labelCurrentActionValue.Visible = false; } else { labelCurrentActionValue.Text = actionTitle; } this.authorizedRoles = authorizedRoles; }
/// <summary> /// Makes server calls, call off the event thread. /// </summary> /// <param name="session"></param> /// <param name="SID"></param> private UserDetails(Session session) { userSid = session.UserSid; userDisplayName = GetDisplayName(session); userName = GetName(session); GetGroupMembership(session); }
// Backward compatibility for Bond.create in XenServer 6.0. public static XenRef<Bond> create(Session session, string _network, List<XenRef<PIF>> _members, string _mac, bond_mode _mode) { if (Helper.APIVersionMeets(session, API_Version.API_1_10)) System.Diagnostics.Debug.Assert(false, "Cannot use this call on XenServer 6.1 or newer."); return XenRef<Bond>.Create(session.proxy.bond_create(session.uuid, (_network != null) ? _network : "", (_members != null) ? Helper.RefListToStringArray(_members) : new string[] { }, (_mac != null) ? _mac : "", bond_mode_helper.ToString(_mode)).parse()); }
/// <summary> /// Backward compatibility for VDI.introduce in XenServer 6.0. /// </summary> public static XenRef<VDI> introduce(Session session, string _uuid, string _name_label, string _name_description, string _sr, vdi_type _type, bool _sharable, bool _read_only, Dictionary<string, string> _other_config, string _location, Dictionary<string, string> _xenstore_data, Dictionary<string, string> _sm_config) { if (Helper.APIVersionMeets(session, API_Version.API_1_10)) System.Diagnostics.Debug.Assert(false, "Cannot use this call on XenServer 6.1 or newer."); return XenRef<VDI>.Create(session.proxy.vdi_introduce(session.uuid, (_uuid != null) ? _uuid : "", (_name_label != null) ? _name_label : "", (_name_description != null) ? _name_description : "", (_sr != null) ? _sr : "", vdi_type_helper.ToString(_type), _sharable, _read_only, Maps.convert_to_proxy_string_string(_other_config), (_location != null) ? _location : "", Maps.convert_to_proxy_string_string(_xenstore_data), Maps.convert_to_proxy_string_string(_sm_config)).parse()); }
public static Session CreateSession(Session session, IXenConnection connection, int timeout) { if (Helpers.DbProxyIsSimulatorUrl(session.Url)) return new Session(session, DbProxy.GetProxy(connection, session.Url), connection); else return new Session(session, connection, timeout); }
protected override void RunWithSession(ref Session session) { this.visible = false; lock (patch) { this.visible = true; this._title = string.Format(Messages.PATCHINGWIZARD_DOWNLOADUPDATE_ACTION_TITLE_DOWNLOADING, patch.Name); if (Cancelling) return; //if it has not been already downloaded if (!AllDownloadedPatches.Any(dp => dp.Key == patch && !string.IsNullOrEmpty(dp.Value)) || !File.Exists(AllDownloadedPatches[patch])) { DownloadFile(ref session); } else { this.visible = false; this._title = string.Format(Messages.PATCHINGWIZARD_DOWNLOADUPDATE_ACTION_TITLE_SKIPPING, patch.Name); } } }
/// <summary> /// Backward compatibility for PIF.db_introduce in XenServer 6.0. /// </summary> public static XenRef<PIF> db_introduce(Session session, string _device, string _network, string _host, string _mac, long _mtu, long _vlan, bool _physical, ip_configuration_mode _ip_configuration_mode, string _ip, string _netmask, string _gateway, string _dns, string _bond_slave_of, string _vlan_master_of, bool _management, Dictionary<string, string> _other_config, bool _disallow_unplug) { if (Helper.APIVersionMeets(session, API_Version.API_1_10)) System.Diagnostics.Debug.Assert(false, "Cannot use this call on XenServer 6.1 or newer."); return XenRef<PIF>.Create(session.proxy.pif_db_introduce(session.uuid, (_device != null) ? _device : "", (_network != null) ? _network : "", (_host != null) ? _host : "", (_mac != null) ? _mac : "", _mtu.ToString(), _vlan.ToString(), _physical, ip_configuration_mode_helper.ToString(_ip_configuration_mode), (_ip != null) ? _ip : "", (_netmask != null) ? _netmask : "", (_gateway != null) ? _gateway : "", (_dns != null) ? _dns : "", (_bond_slave_of != null) ? _bond_slave_of : "", (_vlan_master_of != null) ? _vlan_master_of : "", _management, Maps.convert_to_proxy_string_string(_other_config), _disallow_unplug).parse()); }
private void StartiScsiTarget(XenAPI.Session xenSession, string vdiuuid, bool read_only) { try { string host = XenAPI.Session.get_this_host(xenSession, xenSession.opaque_ref); // Transfer VM for VDI <uuid> Dictionary <string, string> args = new Dictionary <string, string>(); args.Add("vdi_uuid", vdiuuid); args.Add("transfer_mode", "ISCSI"); args.Add("read_only", read_only ? "true" : "false"); args.Add("timeout_minutes", "1"); //Transfer VM IP settings foreach (var kvp in m_networkArgs) { args.Add(kvp.Key, kvp.Value); } string record_handle = Host.call_plugin(xenSession, host, "transfer", "expose", args); Dictionary <string, string> get_record_args = new Dictionary <string, string>(); get_record_args["record_handle"] = record_handle; _pluginrecord = Host.call_plugin(xenSession, host, "transfer", "get_record", get_record_args); _newscsi = true; } catch (Exception ex) { log.Error("Failed to start Transfer VM.", ex); throw new Exception(Messages.ISCSI_START_ERROR, ex); } }
private void StopiScsiTarget(XenAPI.Session xenSession) { if (_iscsisession != null) { try { _iscsisession.Dispose(); } catch (Exception ex) { Log.Debug("iScsiSession dispose failed: {0}, continuing", ex.Message); } } string host = XenAPI.Session.get_this_host(xenSession, xenSession.uuid); Dictionary <string, string> args = new Dictionary <string, string>(); args["record_handle"] = ParsePluginRecordFor("record_handle"); try { string pluginreturn = Host.call_plugin(xenSession, host, "transfer", "unexpose", args); } catch (Exception ex) { Log.Warning("{0} {1}", Messages.ISCSI_SHUTDOWN_ERROR, ex.Message); throw new Exception(Messages.ISCSI_SHUTDOWN_ERROR, ex); } InitializeiSCSI(); Log.Debug("iSCSI.StopScsiTarget: iSCSI Target Destroyed."); }
public static void SetSecretInfo(Session session, Dictionary<string, string> config, string infoKey, string infoValue) { if (string.IsNullOrEmpty(infoKey)) return; if (infoValue == null) { if (config.ContainsKey(infoKey)) { TryToDestroySecret(session, config[infoKey]); config.Remove(infoKey); } } else if (config.ContainsKey(infoKey)) { try { string secretRef = Secret.get_by_uuid(session, config[infoKey]); Secret.set_value(session, secretRef, infoValue); } catch (Failure) { config[infoKey] = Secret.CreateSecret(session, infoValue); } catch (WebException) { config[infoKey] = Secret.CreateSecret(session, infoValue); } } else { config[infoKey] = Secret.CreateSecret(session, infoValue); } }
public void Disconnect(XenAPI.Session xenSession) { try { if (iDisk != null) { iDisk.Dispose(); } iDisk = null; } catch (Exception exn) { Log.Warning("Exception when disposing iDisk", exn); } try { if (_iscsisession != null) { _iscsisession.Dispose(); } _iscsisession = null; } catch (Exception exn) { Log.Warning("Exception when disposing iscsisession", exn); } StopiScsiTarget(xenSession); }
private void StartiScsiTarget(XenAPI.Session xenSession, string vdiuuid, bool read_only) { try { string host = XenAPI.Session.get_this_host(xenSession, xenSession.uuid); // Transfer VM for VDI 1596d05a-f0b5-425c-9d95-74959c6e482c Dictionary <string, string> args = new Dictionary <string, string>(); // cannot change. args.Add("vdi_uuid", vdiuuid); args.Add("transfer_mode", "ISCSI"); args.Add("read_only", read_only ? "true" : "false"); //Transfer VM IP settings foreach (var kvp in m_networkArgs) { args.Add(kvp.Key, kvp.Value); } string record_handle = Host.call_plugin(xenSession, host, "transfer", "expose", args); Dictionary <string, string> get_record_args = new Dictionary <string, string>(); get_record_args["record_handle"] = record_handle; _pluginrecord = Host.call_plugin(xenSession, host, "transfer", "get_record", get_record_args); _newscsi = true; } catch (Exception ex) { Log.Error("{0} {1}", Messages.ISCSI_START_ERROR, ex.Message); throw new Exception(Messages.ISCSI_START_ERROR, ex); } }
protected override void RunWithSession(ref Session session) { XenRef<Task> task = Pool_patch.async_pool_clean(session, _patchRef.opaque_ref); PollTaskForResultAndDestroy(Connection, ref session, task); }
public static void Main(string[] args) { if (args.Length < 3) { System.Console.WriteLine("Required arguments: host-ip username password\n"); return; } // Host information necessary to get started string hostname = args[0]; int port = 80; // default string username = args[1]; string password = args[2]; // Establish a session Session session = new Session(hostname, port); // Authenticate with username and password. The third parameter tells the server which API version we support. session.login_with_password(username, password, API_Version.API_1_3); List<XenRef<VM>> vmRefs = VM.get_all(session); foreach (XenRef<VM> vmRef in vmRefs) { VM vm = VM.get_record(session, vmRef); System.Console.WriteLine("Name: {0}\nvCPUs: {1}\nDescription: {2}\n-", vm.name_label, vm.VCPUs_at_startup, vm.name_description); } }
protected override void RunWithSession(ref Session session) { base.WaitForAgent(ref session, delegate(Session _session) { XenAPI.Host.async_restart_agent(_session, Host.opaque_ref); }); }
protected override void RunWithSession(ref Session session) { List<VM> vmObjs = new List<VM>(); foreach (XenRef<VM> vm in _vms) vmObjs.Add(TryResolveWithTimeout(vm)); PBD.CheckAndPlugPBDsFor(vmObjs); int vmCount = _vms.Count; int i = 0; foreach (VM vm in vmObjs) { XenRef<Task> task = DoPerVM(session, vm); try { PollTaskForResult(Connection, ref session, task, delegate(int progress) { PercentComplete = (progress / vmCount) + ((100 * i) / vmCount); }); i++; } finally { Task.destroy(session, task); } } }
protected override void RunWithSession(ref Session session) { var master = Helpers.GetMaster(host.Connection); var mapping = mappings.Find(m => m.XenServerPatch.Equals(xenServerPatch) && m.MasterHost != null && master != null && m.MasterHost.uuid == master.uuid); if (mapping != null && (mapping.Pool_patch != null || mapping.Pool_update != null)) { XenRef<Task> task = null; if (mapping.Pool_patch != null) { task = Pool_patch.async_apply(session, mapping.Pool_patch.opaque_ref, host.opaque_ref); } else { task = Pool_update.async_apply(session, mapping.Pool_update.opaque_ref, host.opaque_ref); } PollTaskForResultAndDestroy(Connection, ref session, task); } else { if (xenServerPatch != null && master != null) log.ErrorFormat("Mapping not found for patch {0} on master {1}", xenServerPatch.Uuid, master.uuid); throw new Exception("Pool_patch or Pool_update not found."); } }
public void Disconnect(XenAPI.Session xenSession) { try { if (iDisk != null) { iDisk.Dispose(); } iDisk = null; } catch (Exception exn) { log.Debug("Failed to dispose iDisk. Continuing.", exn); } try { if (_iscsisession != null) { _iscsisession.Dispose(); } _iscsisession = null; } catch (Exception exn) { log.Debug("Failed to dispose iScsiSession. Continuing.", exn); } StopiScsiTarget(xenSession); }
/// <summary> /// Backward compatibility for SR.create_new_blob in XenServer 6.0. /// </summary> public static XenRef<Blob> create_new_blob(Session session, string _sr, string _name, string _mime_type) { if (Helper.APIVersionMeets(session, API_Version.API_1_10)) System.Diagnostics.Debug.Assert(false, "Cannot use this call on XenServer 6.1 or newer."); return XenRef<Blob>.Create(session.proxy.sr_create_new_blob(session.uuid, (_sr != null) ? _sr : "", (_name != null) ? _name : "", (_mime_type != null) ? _mime_type : "").parse()); }
/// <summary> /// /// </summary> public XenOvfTransportBase(Uri xenserver, Session session) : this() { _XenServer = xenserver; _XenSession = session; _OwnSession = false; }
protected override void RunWithSession(ref Session session) { string value = XenAPI.Host.call_plugin(session, Host.opaque_ref, "prepare_host_upgrade.py", "main", _arguments); if (value.ToLower() == "true") base.RunWithSession(ref session); else throw new Exception(value); }
/// <summary> /// Initializes a new instance of the <see cref="WlbRecommendations"/> class. /// </summary> /// <param name="vms">The VMs that the recommendations are required for.</param> /// <param name="session">The session.</param> public WlbRecommendations(IEnumerable<VM> vms, Session session) { Util.ThrowIfEnumerableParameterNullOrEmpty(vms, "vms"); Util.ThrowIfParameterNull(session, "session"); _vms = new ReadOnlyCollection<VM>(new List<VM>(vms)); _session = session; }
public sealed override void Apply(Host host, Session session) { foreach (Hotfix hotfix in ComponentHotfixes) { if(hotfix.ShouldBeAppliedTo(host)) hotfix.Apply(host, session); } }
public static void AddCustomField(Session session, IXenConnection connection, CustomFieldDefinition customField) { List<CustomFieldDefinition> customFields = customFieldsCache.GetCustomFields(connection); if (!customFields.Contains(customField)) { customFields.Add(customField); SaveCustomFields(session, connection, customFields); } }
private static void DestroyVM(Session session, VM vm, List<VBD> deleteDisks, IEnumerable<VM> deleteSnapshots) { Exception caught = null; foreach (VM snapshot in deleteSnapshots) { VM snap = snapshot; BestEffort(ref caught, session.Connection.ExpectDisruption, () => { if (snap.power_state == vm_power_state.Suspended) { XenAPI.VM.hard_shutdown(session, snap.opaque_ref); } DestroyVM(session, snap, true); }); } List<XenRef<VDI>> vdiRefs = new List<XenRef<VDI>>(); foreach (XenRef<VBD> vbdRef in vm.VBDs) { VBD vbd = vm.Connection.Resolve(vbdRef); if (vbd == null) continue; if (deleteDisks.Contains(vbd)) { if(vbd.Connection.Resolve(vbd.VDI)!=null) vdiRefs.Add(vbd.VDI); } } //CA-91072: Delete Suspend image VDI VDI suspendVDI = vm.Connection.Resolve(vm.suspend_VDI); if (suspendVDI != null) vdiRefs.Add(vm.suspend_VDI); XenAPI.VM.destroy(session, vm.opaque_ref); foreach (XenRef<VDI> vdiRef in vdiRefs) { XenRef<VDI> vdi = vdiRef; BestEffort(ref caught, session.Connection.ExpectDisruption, () => XenAPI.VDI.destroy(session, vdi.opaque_ref)); //CA-115249. XenAPI could have already deleted the VDI. Destroy suspended VM and destroy snapshot functions are affected. var failure = caught as Failure; if (failure != null && failure.ErrorDescription != null && failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == "HANDLE_INVALID") { log.InfoFormat("VDI:{0} has already been deleted -- ignoring exception.", vdi.opaque_ref); caught = null; } } if (caught != null) throw caught; }
public string bundleUpload(IXenConnection connection, Session session, string uploadToken, System.Threading.CancellationToken cancel) { // Collect the server status report and generate zip file to upload. XenServerHealthCheckBugTool bugTool = new XenServerHealthCheckBugTool(); try { bugTool.RunBugtool(connection, session); } catch (Exception e) { if (session != null) session.logout(); session = null; log.Error(e, e); return ""; } string bundleToUpload = bugTool.outputFile; if(string.IsNullOrEmpty(bundleToUpload) || !File.Exists(bundleToUpload)) { log.ErrorFormat("Server Status Report is NOT collected"); return ""; } // Upload the zip file to CIS uploading server. string upload_url = Registry.HealthCheckUploadDomainName; log.InfoFormat("Upload report to {0}", upload_url); XenServerHealthCheckUpload upload = new XenServerHealthCheckUpload(uploadToken, VERBOSITY_LEVEL, upload_url, connection); string upload_uuid = ""; try { upload_uuid = upload.UploadZip(bundleToUpload, null, cancel); } catch (Exception e) { if (session != null) session.logout(); session = null; log.Error(e, e); return ""; } if (File.Exists(bundleToUpload)) File.Delete(bundleToUpload); // Return the uuid of upload. if(string.IsNullOrEmpty(upload_uuid)) { // Fail to upload the zip to CIS server. log.ErrorFormat("Fail to upload the Server Status Report {0} to CIS server", bundleToUpload); return ""; } return upload_uuid; }
public void SetUp() { mockProxy = new Mock<Proxy>(MockBehavior.Strict); mockConnection = new Mock<IXenConnection>(MockBehavior.Loose); cache = new Cache(); mockConnection.Setup(x => x.Cache).Returns(cache); var session = new Session(mockProxy.Object, mockConnection.Object); mockConnection.Setup(x => x.Session).Returns(session); mockConnection.Setup(x => x.DuplicateSession()).Returns(session); }
//This is a stress test and is therefore being disabled to prevent failures do to lack of memory //[Test] public void TestLoggerWithFewLinesOfLargeData() { Session sesh = new Session(100, ObjectManager.ConnectionFor(id), "host", 12); stream = CreateBigShortStream(); XmlRpcResponseEventArgs args = new XmlRpcResponseEventArgs(Guid.NewGuid(), 1, stream); ObjectManager.MockProxyFor(id).Raise(p => p.ResponseEvent += null, args); ObjectManager.MockProxyFor(id).VerifyAll(); stream.Close(); }
public static void AddTag(Session session, IXenObject o, String tag) { //Program.AssertOffEventThread(); String[] tags = GetTags(o); if (tags != null && Array.IndexOf<String>(tags, tag) > -1) return; o.Do("add_tags", session, o.opaque_ref, tag); }
private void connectBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { this.session = new Session(hostURL, sessionRef); } catch { this.session = null; } }
protected override void RunWithSession(ref Session session) { Host hostObject = TryResolveWithTimeout(_host); PBD.CheckAndPlugPBDsFor(Connection.ResolveAll(hostObject.resident_VMs)); Host.disable(session, _host.opaque_ref); Status = Messages.PLAN_ACTION_STATUS_MIGRATING_VMS_FROM_HOST; XenRef<Task> task = Host.async_evacuate(session, _host.opaque_ref); PollTaskForResultAndDestroy(Connection, ref session, task); }
public bool Connect(string server, int port, string vm_uuid, string username, string password, int width, int height, bool show_border) { // reinitiailize the VNC Control initSubControl(width, height, true, show_border); m_vncClient.ErrorOccurred += ConnectionErrorHandler; try { // Create a new XenAPI session m_session = new Session(Session.STANDARD_TIMEOUT, server, port); // Authenticate with username and password passed in. // The third parameter tells the server which API version we support. m_session.login_with_password(username, password, API_Version.LATEST); m_vncPassword = password.ToCharArray(); // Find the VM in question XenRef <VM> vmRef = VM.get_by_uuid(m_session, vm_uuid); m_sourceVM = VM.get_record(m_session, vmRef); // Check if this VM is PV or HVM m_sourceIsPV = (m_sourceVM.PV_bootloader.Length != 0); /* No PV bootloader specified implies HVM */ // Get the console that uses the RFB (VNC) protocol List <XenRef <XenAPI.Console> > consoleRefs = VM.get_consoles(m_session, vmRef); XenAPI.Console console = null; foreach (XenRef <XenAPI.Console> consoleRef in consoleRefs) { console = XenAPI.Console.get_record(m_session, consoleRef); if (console.protocol == console_protocol.rfb) { break; } console = null; } if (console != null) { //ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectToConsole), new KeyValuePair<VNCGraphicsClient, XenAPI.Console>(m_vncClient, console)); ConnectHostedConsole(m_vncClient, console, m_session.uuid); } // done with this session, log it out m_session.logout(); } catch (Exception exn) { // call the expcetion handler directly this.ConnectionErrorHandler(this, exn); } return(m_vncClient.Connected); }
protected override void RunWithSession(ref Session session) { _host.Connection.ExpectDisruption = true; try { base.WaitForReboot(ref session, _session => XenAPI.Host.async_reboot(_session, Host.opaque_ref)); foreach (var host in _host.Connection.Cache.Hosts) host.CheckAndPlugPBDs(); // Wait for PBDs to become plugged on all hosts } finally { _host.Connection.ExpectDisruption = false; } }
private static void DestroyVM(Session session, VM vm, List<VBD> deleteDisks, IEnumerable<VM> deleteSnapshots) { Exception caught = null; foreach (VM snapshot in deleteSnapshots) { VM snap = snapshot; BestEffort(ref caught, session.Connection.ExpectDisruption, () => { if (snap.power_state == vm_power_state.Suspended) { XenAPI.VM.hard_shutdown(session, snap.opaque_ref); } DestroyVM(session, snap, true); }); } List<XenRef<VDI>> vdiRefs = new List<XenRef<VDI>>(); foreach (XenRef<VBD> vbdRef in vm.VBDs) { VBD vbd = vm.Connection.Resolve(vbdRef); if (vbd == null) continue; if (deleteDisks.Contains(vbd)) { if(vbd.Connection.Resolve(vbd.VDI)!=null) vdiRefs.Add(vbd.VDI); } } //CA-91072: Delete Suspend image VDI VDI suspendVDI = vm.Connection.Resolve(vm.suspend_VDI); if (suspendVDI != null) vdiRefs.Add(vm.suspend_VDI); XenAPI.VM.destroy(session, vm.opaque_ref); foreach (XenRef<VDI> vdiRef in vdiRefs) { XenRef<VDI> vdi = vdiRef; BestEffort(ref caught, session.Connection.ExpectDisruption, () => XenAPI.VDI.destroy(session, vdi.opaque_ref)); } if (caught != null) throw caught; }
public VbdSaveAndPlugAction(VM vm, XenAPI.VBD vbd, string vdiName, XenAPI.Session session, bool supress, Action showMustRebootBoxCD, Action showVBDWarningBox) : base(vm.Connection, string.Format(Messages.ATTACHING_VIRTUAL_DISK, vdiName, vm.Name), "", supress) { _ShowVBDWarningBox = showVBDWarningBox; _ShowMustRebootBoxCD = showMustRebootBoxCD; VM = vm; this.vbd = vbd; // Preserve existing session if provided. if (session != null) { this.Session = session; } ApiMethodsToRoleCheck.Add("vbd.async_plug"); ApiMethodsToRoleCheck.Add("vbd.set_userdevice"); }
protected override void RunWithSession(ref Session session) { var master = Helpers.GetMaster(Connection); var mapping = mappings.Find(m => m.XenServerPatch.Equals(patch) && m.MasterHost != null && master != null && m.MasterHost.uuid == master.uuid); if (mapping != null && (mapping.Pool_patch != null || mapping.Pool_update != null)) { foreach (var host in hosts) { if (Cancelling) { throw new CancelledException(); } try { PatchPrecheckCheck check = null; if (mapping.Pool_patch != null) { check = new PatchPrecheckCheck(host, mapping.Pool_patch); } else { check = new PatchPrecheckCheck(host, mapping.Pool_update); } var problems = check.RunAllChecks(); Diagnostics.Problems.Problem problem = null; if (problems != null && problems.Count > 0) problem = problems[0]; if (problem != null) { throw new Exception(string.Format("{0}: {1}. {2}", host, problem.Title, problem.Description)); } } catch (Exception ex) { log.Error(string.Format("Precheck failed on host {0}", host.Name), ex); throw ex; } } } }
public static VM FindiSCSI(XenAPI.Session xenSession) { Dictionary <XenRef <VM>, VM> iSCSIDict = VM.get_all_records(xenSession); foreach (XenRef <VM> key in iSCSIDict.Keys) { if (iSCSIDict[key].is_a_template) { if (iSCSIDict[key].other_config.ContainsKey("transfervm") && iSCSIDict[key].other_config["transfervm"] == "true") { return(iSCSIDict[key]); } } } return(null); }
/// <summary> /// Makes server calls, call off the event thread. /// </summary> /// <param name="session"></param> private UserDetails(Session session) { _session = session; userSid = session.UserSid; try { Subject subj = new Subject(); subj.other_config = Auth.get_subject_information_from_identifier(session, userSid); userDisplayName = subj.DisplayName; userName = subj.SubjectName; groupMembershipSids = Auth.get_group_membership(session, userSid); } catch(Failure) { } }
private void ProcessRecordOpenDatabase(string vdi) { if (!ShouldProcess(vdi, "VDI.open_database")) { return; } RunApiCall(() => { var contxt = _context as XenVDIActionOpenDatabaseDynamicParameters; if (contxt != null && contxt.Async) { taskRef = XenAPI.VDI.async_open_database(session, vdi); if (PassThru) { XenAPI.Task taskObj = null; if (taskRef != "OpaqueRef:NULL") { taskObj = XenAPI.Task.get_record(session, taskRef.opaque_ref); taskObj.opaque_ref = taskRef.opaque_ref; } WriteObject(taskObj, true); } } else { string objRef = XenAPI.VDI.open_database(session, vdi); if (PassThru) { XenAPI.Session obj = null; if (objRef != "OpaqueRef:NULL") { obj = XenAPI.Session.get_record(session, objRef); obj.opaque_ref = objRef; } WriteObject(obj, true); } } }); }
private double GetAgentStartTime(Session session) { Dictionary<String, String> other_config = XenAPI.Host.get_other_config(session, Host); if (other_config == null) return 0.0; if (!other_config.ContainsKey(XenAPI.Host.AGENT_START_TIME)) return 0.0; double agentStartTime; if (!double.TryParse(other_config[XenAPI.Host.AGENT_START_TIME], NumberStyles.Number, CultureInfo.InvariantCulture, out agentStartTime)) return 0.0; return agentStartTime; }
private void StopiScsiTarget(XenAPI.Session xenSession) { try { string host = XenAPI.Session.get_this_host(xenSession, xenSession.opaque_ref); Dictionary <string, string> args = new Dictionary <string, string>(); string handle; if (!TryParsePluginRecordFor(_pluginrecord, "record_handle", out handle)) { log.Debug("Transfer VM was not started. Will not attempt to shut it down."); return; } args["record_handle"] = handle; Host.call_plugin(xenSession, host, "transfer", "unexpose", args); log.Debug("iSCSI.StopScsiTarget: iSCSI Target Destroyed."); } catch (Exception ex) { log.Warn("Failed to shutdown Transfer VM.", ex); throw new Exception(Messages.ISCSI_SHUTDOWN_ERROR, ex); } }
/// <summary> /// Get the install_time field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static DateTime get_install_time(Session session, string _vm_metrics) { return(session.proxy.vm_metrics_get_install_time(session.uuid, _vm_metrics ?? "").parse()); }
/// <summary> /// Get the last_updated field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static DateTime get_last_updated(Session session, string _vm_metrics) { return(session.proxy.vm_metrics_get_last_updated(session.uuid, _vm_metrics ?? "").parse()); }
/// <summary> /// Get the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary <string, string> get_other_config(Session session, string _vm_metrics) { return(Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_other_config(session.uuid, _vm_metrics ?? "").parse())); }
public DiskStream Connect(XenAPI.Session xenSession, string vdiuuid, bool read_only) { StartiScsiTarget(xenSession, vdiuuid, read_only); string ipaddress, port, targetGroupTag, username, password; if (!TryParsePluginRecordFor(_pluginrecord, "ip", out ipaddress)) { throw new Exception(Messages.ISCSI_ERROR_NO_IPADDRESS); } TryParsePluginRecordFor(_pluginrecord, "port", out port); int ipport = Convert.ToInt32(port); TryParsePluginRecordFor(_pluginrecord, "isci_lun", out targetGroupTag); TryParsePluginRecordFor(_pluginrecord, "username", out username); TryParsePluginRecordFor(_pluginrecord, "password", out password); Initiator initiator = new Initiator(); if (username != null && password != null) { initiator.SetCredentials(username, password); } int iSCSIConnectRetry = Properties.Settings.Default.iSCSIConnectRetry; bool iSCSIConnected = false; while (!iSCSIConnected && iSCSIConnectRetry > 0) { if (Cancel) { throw new OperationCanceledException(); } try { log.DebugFormat("Connecting virtual disk {0}... ", vdiuuid); TargetAddress ta = new TargetAddress(ipaddress, ipport, targetGroupTag); TargetInfo[] targets = initiator.GetTargets(ta); log.InfoFormat("iSCSI.Connect found {0} targets, connecting to: {1}", targets.Length, targets[0].Name); _iscsisession = initiator.ConnectTo(targets[0]); iSCSIConnected = true; } catch (Exception ex) { log.Error($"Failed to connect to VDI {vdiuuid} over iSCSI.", ex); Thread.Sleep(new TimeSpan(0, 0, 5)); iSCSIConnectRetry--; } } if (!iSCSIConnected) { throw new Exception(Messages.ISCSI_ERROR); } long lun = 0; try { LunInfo[] luns = _iscsisession.GetLuns(); if (_newscsi) { string idx; TryParsePluginRecordFor(_pluginrecord, "iscsi_lun", out idx); long lunIdx = Convert.ToInt32(idx); lun = luns[lunIdx].Lun; } log.InfoFormat("iSCSI.Connect found {0} luns, looking for block storage.", luns.Length); foreach (LunInfo iLun in luns) { if (iLun.DeviceType == LunClass.BlockStorage) { if (_newscsi && iLun.Lun == lun) { break; } lun = iLun.Lun; break; } } } catch (Exception e) { log.Error("Could not determine LUN", e); throw; } log.InfoFormat("iSCSI.Connect, found on lun: {0}", lun); try { iDisk = _iscsisession.OpenDisk(lun); // Use our own DiskStream class to workaround a bug in DiscUtils.DiskStream. return(new DiskStream(_iscsisession, lun, (read_only ? FileAccess.Read : FileAccess.ReadWrite))); } catch (Exception ex) { log.Error("Failed to open virtual disk.", ex); throw new Exception(Messages.ISCSI_ERROR_CANNOT_OPEN_DISK, ex); } }
/// <summary> /// Get the VCPUs/params field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary <string, string> get_VCPUs_params(Session session, string _vm_metrics) { return(Maps.convert_from_proxy_string_string(session.proxy.vm_metrics_get_vcpus_params(session.uuid, _vm_metrics ?? "").parse())); }
public bool ConnectConsole(string consoleuri, int width, int height, bool show_border) { //reinitialise the VNC Control initSubControl(width, height, true, show_border); m_vncClient.ErrorOccurred += ConnectionErrorHandler; try { XenAPI.Console console = new XenAPI.Console(); console.protocol = console_protocol.rfb; console.location = consoleuri; Uri uri = new Uri(consoleuri); char[] delims = { '&', '=', '?' }; string qargs = uri.Query; string session_id = ""; string vm_Opref = ""; string console_ref = ""; string[] args = qargs.Split(delims); int x = -1; int y = -1; int z = -1; int count = 0; foreach (string s in args) { if (String.Equals(s, "session_id", StringComparison.Ordinal)) { //The session_id value must be one greater in array x = count + 1; } else if (String.Equals(s, "ref", StringComparison.Ordinal)) { //The OpaqueRef for vnc console must be one greater in array y = count + 1; } else if (String.Equals(s, "uuid", StringComparison.Ordinal)) { //The uuid was passed for the vnc console - it must be one //greater in the array. z = count + 1; } count++; } //Checks for incorrect parsing of the console URL if (x == -1 || x == count) { this.ConnectionErrorHandler(this, new System.ApplicationException("Error: The session ID has been incorrectly parsed.")); } else { session_id = args[x]; } if (console != null) { try { m_session = new Session("http://" + uri.Host, session_id); } catch (XenAPI.Failure f) { if (f.ErrorDescription[0] == HOST_IS_SLAVE) { string m_address = f.ErrorDescription[1]; m_session = new Session("http://" + m_address, session_id); } } if ((y == -1 && z == -1) || (y == count && z == count)) { //Check for the error case where neither uuid or vm_reference have been supplied. this.ConnectionErrorHandler(this, new System.ApplicationException("Error: The console reference has been incorrectly parsed.")); } else if (y != -1 && y != count) { //The console reference has been provided. console_ref = args[y]; } else if (z != -1 && z != count) { //The console uuid has been supplied instead, we must get the VM reference. console_ref = XenAPI.Console.get_by_uuid(m_session, args[z]); } vm_Opref = XenAPI.Console.get_VM(m_session, console_ref); m_sourceVM = VM.get_record(m_session, vm_Opref); // Check if this VM is PV or HVM m_sourceIsPV = (m_sourceVM.PV_bootloader.Length != 0); ConnectHostedConsole(m_vncClient, console, session_id); } } catch (Exception exn) { //call the exception handler directly this.ConnectionErrorHandler(this, exn); } return(m_vncClient.Connected); }
/// <summary> /// Add the given key-value pair to the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vm_metrics, string _key, string _value) { session.proxy.vm_metrics_add_to_other_config(session.uuid, _vm_metrics ?? "", _key ?? "", _value ?? "").parse(); }
/// <summary> /// Set the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vm_metrics, Dictionary <string, string> _other_config) { session.proxy.vm_metrics_set_other_config(session.uuid, _vm_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); }
/// <summary> /// Return a list of all the VM_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List <XenRef <VM_metrics> > get_all(Session session) { return(XenRef <VM_metrics> .Create(session.proxy.vm_metrics_get_all(session.uuid).parse())); }
/// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VM_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vm_metrics, string _key) { session.proxy.vm_metrics_remove_from_other_config(session.uuid, _vm_metrics ?? "", _key ?? "").parse(); }
/// <summary> /// Get all the VM_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary <XenRef <VM_metrics>, VM_metrics> get_all_records(Session session) { return(XenRef <VM_metrics> .Create <Proxy_VM_metrics>(session.proxy.vm_metrics_get_all_records(session.uuid).parse())); }
/// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="hosts"></param> /// <returns></returns> private void btnSnapshotRevert_Click(object sender, EventArgs e) { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); string ipAddr = string.Empty; if (!string.IsNullOrEmpty(this.txtBxIPAddr.Text)) { ipAddr = this.txtBxIPAddr.Text; } else { ipAddr = string.Empty; } XenAPI.Session session = new XenAPI.Session(ipAddr, 443); session.login_with_password("root", "dpsvl123", "", "XenSDKSample"); var vmRecords = VM.get_all_records(session); var vmRef = (from KeyValuePair <XenRef <VM>, VM> kvp in vmRecords let theVm = kvp.Value where !theVm.is_a_template && !theVm.is_control_domain && theVm.name_label.ToLower().Contains("Window_7_64_M1".ToLower()) select kvp.Key).FirstOrDefault(); var vmRefValue = (from KeyValuePair <XenRef <VM>, VM> kvp in vmRecords let theVm = kvp.Value where !theVm.is_a_template && !theVm.is_control_domain && theVm.name_label.ToLower().Contains("window") select kvp.Value).FirstOrDefault(); var vmRefSnapShot = (from KeyValuePair <XenRef <VM>, VM> kvp in vmRecords let theVm = kvp.Value where !theVm.is_a_template && !theVm.is_control_domain && theVm.name_label.ToLower().Contains("inita") select kvp.Value).FirstOrDefault(); if (vmRef == null) { MessageBox.Show("Cannot find a halted linux VM. Please create one."); } VM vm = VM.get_record(session, vmRef); var snapshotRef = VM.get_snapshots(session, vmRef).FirstOrDefault(); //var snapshotUUID = VM.get_uuid(session, snapshotRef); //VM.destroy(session, snapshotRef); //MessageBox.Show("Here is the vm I destroyed! "); //var newVM = VM.snapshot(session, vmRef, "inita"); //VM vm = VM.get_record(session, newVM); //VM.shutdown(session, vmRef); //VM.start(session, vmRef, false, true); VM.revert(session, snapshotRef); //MessageBox.Show("The current state " + VM.get_power_state(session, vmRef)); VM.resume(session, vmRef, false, true); //VM.start(session, vmRef, false, true); //MessageBox.Show("The current state " + VM.get_power_state(session, vmRef)); //MessageBox.Show("Here is the vm I want to revert "+vm.name_label); //MessageBox.Show("Here is the vm I created" + vm.name_label); MessageBox.Show("Here is the vm I rebooted" + vm.name_label); session.logout(); //GC.SuppressFinalize(this); }
public VbdSaveAndPlugAction(VM vm, XenAPI.VBD vbd, string vdiName, XenAPI.Session session, bool installingTools, bool supress, Action showMustRebootBoxCD, Action showVBDWarningBox) : this(vm, vbd, vdiName, session, supress, showMustRebootBoxCD, showVBDWarningBox) { InstallingTools = installingTools; }
/// <summary> /// Get the state field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static string[] get_state(Session session, string _vm_metrics) { return((string [])session.proxy.vm_metrics_get_state(session.uuid, _vm_metrics ?? "").parse()); }
/// <summary> /// Get the nomigrate field of the given VM_metrics. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static bool get_nomigrate(Session session, string _vm_metrics) { return((bool)session.proxy.vm_metrics_get_nomigrate(session.uuid, _vm_metrics ?? "").parse()); }
/// <summary> /// Get the VCPUs/flags field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary <long, string[]> get_VCPUs_flags(Session session, string _vm_metrics) { return(Maps.convert_from_proxy_long_string_array(session.proxy.vm_metrics_get_vcpus_flags(session.uuid, _vm_metrics ?? "").parse())); }
/// <summary> /// Get the nested_virt field of the given VM_metrics. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static bool get_nested_virt(Session session, string _vm_metrics) { return((bool)session.proxy.vm_metrics_get_nested_virt(session.uuid, _vm_metrics ?? "").parse()); }
/// <summary> /// scan each ip address (from the guest agent) for an open port /// </summary> /// <param name="port"></param> private String PollPort(int port, bool vnc) { try { Log.Debug("PollPort called"); if (m_sourceVM == null) { return(null); } VM vm = m_sourceVM; XenRef <VM_guest_metrics> guestMetricsRef = vm.guest_metrics; if (guestMetricsRef == null) { return(null); } VM_guest_metrics metrics = XenAPI.VM_guest_metrics.get_record(m_session, vm.guest_metrics); if (metrics == null) { return(null); } Dictionary <string, string> networks = metrics.networks; if (networks == null) { return(null); } List <String> ipAddresses = new List <String>(); foreach (String key in networks.Keys) { if (key.EndsWith("ip")) { ipAddresses.Add(networks[key]); } } foreach (String ipAddress in ipAddresses) { try { Stream s = connectGuest(ipAddress, port); if (vnc) { //SetPendingVNCConnection(s); } else { s.Close(); } return(ipAddress); } catch (Exception exn) { Log.Debug(exn); } } } catch (WebException) { // xapi has gone away. } catch (IOException) { // xapi has gone away. } catch (XenAPI.Failure exn) { if (exn.ErrorDescription[0] == HANDLE_INVALID) { // HANDLE_INVALID is fine -- the guest metrics are not there yet. } else if (exn.ErrorDescription[0] == SESSION_INVALID) { // SESSION_INVALID is fine -- these will expire from time to time. // We need to invalidate the session though. //lock (activeSessionLock) //{ m_session = null; //} } else { Log.Warn("Exception while polling VM for port " + port + ".", exn); } } catch (Exception e) { Log.Warn("Exception while polling VM for port " + port + ".", e); } return(null); }
public XenOvfTransport.DiskStream Connect(XenAPI.Session xenSession, string vdiuuid, bool read_only) { int iSCSIConnectRetry = Properties.Settings.Default.iSCSIConnectRetry; bool iSCSIConnected = false; StartiScsiTarget(xenSession, vdiuuid, read_only); string ipaddress = ParsePluginRecordFor("ip"); int ipport = Convert.ToInt32(ParsePluginRecordFor("port")); string targetGroupTag = ParsePluginRecordFor("isci_lun"); if (ipaddress == null) { throw new NullReferenceException(Messages.ISCSI_ERROR_NO_IPADDRESS); } string username = ParsePluginRecordFor("username"); string password = ParsePluginRecordFor("password"); Initiator initiator = new Initiator(); if (username != null && password != null) { initiator.SetCredentials(username, password); } while (!iSCSIConnected && iSCSIConnectRetry > 0) { if (Cancel) { throw new OperationCanceledException(); } try { Log.Debug(Messages.FILES_TRANSPORT_SETUP, vdiuuid); TargetAddress ta = new TargetAddress(ipaddress, ipport, targetGroupTag); TargetInfo[] targets = initiator.GetTargets(ta); Log.Info("iSCSI.Connect found {0} targets, connecting to: {1}", targets.Length, targets[0].Name); _iscsisession = initiator.ConnectTo(targets[0]); iSCSIConnected = true; } catch (Exception ex) { Log.Error("{0} {1}", Messages.ISCSI_ERROR, ex.Message); Thread.Sleep(new TimeSpan(0, 0, 5)); iSCSIConnectRetry--; } } if (!iSCSIConnected) { throw new Exception(Messages.ISCSI_ERROR); } long lun = 0; try { LunInfo[] luns = _iscsisession.GetLuns(); if (_newscsi) { long lunIdx = Convert.ToInt32(ParsePluginRecordFor("iscsi_lun")); lun = luns[lunIdx].Lun; } Log.Info("iSCSI.Connect found {0} luns, looking for block storage.", luns.Length); foreach (LunInfo iLun in luns) { if (iLun.DeviceType == LunClass.BlockStorage) { if (_newscsi && iLun.Lun == lun) { break; } lun = iLun.Lun; break; } } } catch (Exception) { Log.Error("Could not determin LUN"); throw; } Log.Info("iSCSI.Connect, found on lun: {0}", lun); try { iDisk = _iscsisession.OpenDisk(lun); // Use our own DiskStream class to workaround a bug in DiscUtils.DiskStream. return(new XenOvfTransport.DiskStream(_iscsisession, lun, (read_only ? FileAccess.Read : FileAccess.ReadWrite))); } catch (Exception ex) { Log.Error("{0} {1}", Messages.ISCSI_ERROR_CANNOT_OPEN_DISK, ex.Message); throw new Exception(Messages.ISCSI_ERROR_CANNOT_OPEN_DISK, ex); } }