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); } }
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); }
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); // Information about the hosts PrintHostInformation(session); // Information about physical network interfaces PrintPhysicalInterfaces(session); // All the storage repositories available PrintStorageRepositories(session); // Print per VM information PrintVMInformation(session); // watch it all before it vanishes System.Console.WriteLine("Hit any key to exit\n"); System.Console.ReadKey(); }
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 = 443; // default string username = args[1]; string password = args[2]; // Establish a session ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; // Trust all certificates: DO NOT USE IN PRODUCTION CODE! ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 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); // Choose a VM at random which is not a template or control domain and which is currently switched off. XenRef<VM> chosenRef = null; foreach (KeyValuePair<XenRef<VM>, VM> kvp in VM.get_all_records(session)) { VM vm = kvp.Value; if (!vm.is_a_template && !vm.is_control_domain && vm.power_state == vm_power_state.Halted) { chosenRef = kvp.Key; break; } } string cloneVM = null; if (chosenRef != null) { // clone the vm VM chosenVM = VM.get_record(session, chosenRef); System.Console.WriteLine("Cloning VM '{0}'...", chosenVM.name_label); cloneVM = VM.clone(session, chosenRef, string.Format("Cloned VM (from '{0}')", chosenVM.name_label)); System.Console.WriteLine("Cloned VM; new VM is {0}", cloneVM); // set its description VM.set_name_description(session, cloneVM, "Another cloned VM"); System.Console.WriteLine("VM name: {0} Description: {1} Power State: {2}", VM.get_name_label(session, cloneVM), VM.get_name_description(session, cloneVM), VM.get_power_state(session, cloneVM)); // start the clone in a paused state System.Console.WriteLine("Starting VM paused..."); VM.start(session, cloneVM, true, true); System.Console.WriteLine("VM Power State: {0}", VM.get_power_state(session, cloneVM)); // unpause it System.Console.WriteLine("Unpausing VM..."); VM.unpause(session, cloneVM); System.Console.WriteLine("VM Power State: {0}", VM.get_power_state(session, cloneVM)); // now suspend it System.Console.WriteLine("Suspending VM..."); VM.suspend(session, cloneVM); System.Console.WriteLine("VM Power State: {0}", VM.get_power_state(session, cloneVM)); // and then resume System.Console.WriteLine("Resuming VM..."); VM.resume(session, cloneVM, false, true); System.Console.WriteLine("VM Power State: {0}", VM.get_power_state(session, cloneVM)); // and then shutdown System.Console.WriteLine("Forcing shutdown VM..."); VM.hard_shutdown(session, cloneVM); System.Console.WriteLine("VM Power State: {0}", VM.get_power_state(session, cloneVM)); // now destroy it System.Console.WriteLine("Destroying VM..."); VM.destroy(session, cloneVM); System.Console.WriteLine("VM destroyed."); } else { System.Console.WriteLine("No suitable VMs found (please install one)"); } // watch it all before it vanishes System.Console.WriteLine("\nHit any key to exit\n"); System.Console.ReadKey(); }
protected override void ProcessRecord() { if ((Url == null || Url.Length == 0) && (Server == null || Server.Length == 0)) { ThrowTerminatingError(new ErrorRecord( new Exception("You must provide a URL, Name or IP Address for the XenServer."), "", ErrorCategory.InvalidArgument, null)); } if (Creds == null && (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) && (OpaqueRef == null || OpaqueRef.Length == 0)) { Creds = Host.UI.PromptForCredential("XenServer Credential Request", "", string.IsNullOrEmpty(UserName) ? "root" : UserName, ""); if (Creds == null) { // Just bail out at this point, they've clicked cancel on the credentials pop up dialog ThrowTerminatingError(new ErrorRecord( new Exception("Credentials must be supplied when connecting to the XenServer."), "", ErrorCategory.InvalidArgument, null)); } } string connUser = ""; string connPassword = ""; if (OpaqueRef == null || OpaqueRef.Length == 0) { if (Creds == null) { connUser = UserName; connPassword = Password; SecureString secPwd = new SecureString(); foreach (char ch in connPassword) secPwd.AppendChar(ch); Creds = new PSCredential(UserName, secPwd); } else { connUser = Creds.UserName.StartsWith("\\") ? Creds.GetNetworkCredential().UserName : Creds.UserName; IntPtr ptrPassword = Marshal.SecureStringToBSTR(Creds.Password); connPassword = Marshal.PtrToStringBSTR(ptrPassword); Marshal.FreeBSTR(ptrPassword); } } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if (Url == null || Url.Length == 0) { Url = new string[Server.Length]; for (int i = 0; i < Server.Length; i++) Url[i] = CommonCmdletFunctions.GetUrl(Server[i], Port); } if (OpaqueRef == null) { OpaqueRef = new string[Url.Length]; } else { if (OpaqueRef.Length != Url.Length) ThrowTerminatingError(new ErrorRecord( new Exception("The number of opaque references provided should be the same as the number of xenservers."), "", ErrorCategory.InvalidArgument, null)); } Dictionary<string, Session> sessions = CommonCmdletFunctions.GetAllSessions(this); Dictionary<string, Session> newSessions = new Dictionary<string, Session>(); for (int i = 0; i < Url.Length; i++) { Session session; if (string.IsNullOrEmpty(OpaqueRef[i])) { session = new Session(Url[i]); var apiVersionString = XenAPI.Helper.APIVersionString(session.APIVersion); session.login_with_password(connUser, connPassword, apiVersionString, "XenServerPSModule/" + apiVersionString); } else { session = new Session(Url[i], OpaqueRef[i]); } session.Tag = Creds; session.opaque_ref = session.uuid; sessions[session.opaque_ref] = session; newSessions[session.opaque_ref] = session; if (i > 0) continue; //set the first of the specified connections as default if (SetDefaultSession) { WriteVerbose(string.Format("Setting connection {0} ({1}) as default.", session.Url, session.opaque_ref)); CommonCmdletFunctions.SetDefaultXenSession(this, session); } } CommonCmdletFunctions.SetAllSessions(this, sessions); if (PassThru) WriteObject(newSessions.Values, true); }
public void runUpload(System.Threading.CancellationToken serviceStop) { DateTime startTime = DateTime.UtcNow; string uploadToken = ""; Session session = new Session(connection.Hostname, 80); session.APIVersion = API_Version.LATEST; try { session.login_with_password(connection.Username, connection.Password); connection.LoadCache(session); var pool = Helpers.GetPoolOfOne(connection); if (pool != null) { try { string opaqueref = Secret.get_by_uuid(session, pool.HealthCheckSettings.UploadTokenSecretUuid); uploadToken = Secret.get_value(session, opaqueref); } catch (Exception e) { log.Error("Exception getting the upload token from the xapi secret", e); uploadToken = null; } } if (string.IsNullOrEmpty(uploadToken)) { if (session != null) session.logout(); session = null; log.ErrorFormat("The upload token is not retrieved for {0}", connection.Hostname); updateHealthCheckSettings(false, startTime); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); return; } } catch (Exception e) { if (session != null) session.logout(); session = null; log.Error(e, e); updateHealthCheckSettings(false, startTime); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); return; } try { CancellationTokenSource cts = new CancellationTokenSource(); Func<string> upload = delegate() { try { return bundleUpload(connection, session, uploadToken, cts.Token); } catch (OperationCanceledException) { return ""; } }; System.Threading.Tasks.Task<string> task = new System.Threading.Tasks.Task<string>(upload); task.Start(); // Check if the task runs to completion before timeout. for (int i = 0; i < TIMEOUT; i += INTERVAL) { // If the task finishes, set HealthCheckSettings accordingly. if (task.IsCompleted || task.IsCanceled || task.IsFaulted) { if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion) { string upload_uuid = task.Result; if (!string.IsNullOrEmpty(upload_uuid)) updateHealthCheckSettings(true, startTime, upload_uuid); else updateHealthCheckSettings(false, startTime); } else updateHealthCheckSettings(false, startTime); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); return; } // If the main thread (XenServerHealthCheckService) stops, // set the cancel token to notify the working task to return. if (serviceStop.IsCancellationRequested) { cts.Cancel(); updateHealthCheckSettings(false, startTime); task.Wait(); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); return; } System.Threading.Thread.Sleep(INTERVAL); } // The task has run for 24h, cancel the task and mark it as a failure upload. cts.Cancel(); updateHealthCheckSettings(false, startTime); task.Wait(); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); return; } catch (Exception e) { if (session != null) session.logout(); session = null; log.Error(e, e); server.task = null; ServerListHelper.instance.UpdateServerInfo(server); } }
public void updateHealthCheckSettings(bool success, DateTime time, string uploadUuid = "") { Session session = new Session(connection.Hostname, 80); session.login_with_password(connection.Username, connection.Password); connection.LoadCache(session); // Round-trip format time DateTime rtime = DateTime.SpecifyKind(time, DateTimeKind.Utc); string stime = HealthCheckSettings.DateTimeToString(rtime); // record upload_uuid, // release the lock, // set the time of LAST_SUCCESSFUL_UPLOAD or LAST_FAILED_UPLOAD Dictionary<string, string> config = Pool.get_health_check_config(session, connection.Cache.Pools[0].opaque_ref); config[HealthCheckSettings.UPLOAD_LOCK] = ""; if (success) { config[HealthCheckSettings.LAST_SUCCESSFUL_UPLOAD] = stime; config[HealthCheckSettings.UPLOAD_UUID] = uploadUuid; // reset the NEW_UPLOAD_REQUEST field, if the current successful upload was started after the request DateTime newUploadRequestTime; if (HealthCheckSettings.TryParseStringToDateTime(config[HealthCheckSettings.NEW_UPLOAD_REQUEST], out newUploadRequestTime)) { if (rtime > newUploadRequestTime) config[HealthCheckSettings.NEW_UPLOAD_REQUEST] = ""; } } else config[HealthCheckSettings.LAST_FAILED_UPLOAD] = stime; Pool.set_health_check_config(session, connection.Cache.Pools[0].opaque_ref, config); if (session != null) session.logout(); session = null; }
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 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); } } }
public void updateCallHomeSettings(bool success, DateTime time, string uploadUuid = "") { Session session = new Session(connection.Hostname, 80); session.login_with_password(connection.Username, connection.Password); connection.LoadCache(session); // Round-trip format time DateTime rtime = DateTime.SpecifyKind(time, DateTimeKind.Utc); string stime = CallHomeSettings.DateTimeToString(rtime); // record upload_uuid, // release the lock, // set the time of LAST_SUCCESSFUL_UPLOAD or LAST_FAILED_UPLOAD Dictionary<string, string> config = Pool.get_health_check_config(session, connection.Cache.Pools[0].opaque_ref); config[CallHomeSettings.UPLOAD_LOCK] = ""; if (success) { config[CallHomeSettings.LAST_SUCCESSFUL_UPLOAD] = stime; config[CallHomeSettings.UPLOAD_UUID] = uploadUuid; } else config[CallHomeSettings.LAST_FAILED_UPLOAD] = stime; Pool.set_health_check_config(session, connection.Cache.Pools[0].opaque_ref, config); if (session != null) session.logout(); session = null; }
/// <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); }
// Test API for the harness public Dictionary<String, String> ListConsoles(String server, int port, String username, String password) { XenAPI.Session session = new Session(Session.STANDARD_TIMEOUT, server, port); Dictionary<String, String> dict = new Dictionary<String, String>(); // Authenticate with username and password. The third parameter tells the server which API version we support. session.login_with_password(username, password, API_Version.LATEST); List<XenRef<XenAPI.Console>> consoleRefs = XenAPI.Console.get_all(session); foreach (XenRef<XenAPI.Console> consoleRef in consoleRefs) { XenAPI.Console console = XenAPI.Console.get_record(session, consoleRef); XenAPI.VM vm = XenAPI.VM.get_record(session, console.VM); dict.Add(vm.uuid, vm.name_label); } return dict; }
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; }