protected VimClient ConnectServer(string viServer, string viUser, string viPassword) { // // Establish a connetion to the provided sdk server // VimClient vimClient = new VimClient(); ServiceContent vimServiceContent = new ServiceContent(); UserSession vimSession = new UserSession(); // // Connect over https to the /sdk page // try { vimClient.Connect(viServer); vimSession = vimClient.Login(viUser, viPassword); vimServiceContent = vimClient.ServiceContent; return vimClient; } catch (VimException ex) { // // VMware Exception occurred // txtErrors.Text = "A server fault of type " + ex.MethodFault.GetType().Name + " with message '" + ex.Message + "' occured while performing requested operation."; Error_Panel.Visible = true; return null; } catch (Exception e) { // // Regular Exception occurred // txtErrors.Text = "A server fault of type " + e.GetType().Name + " with message '" + e.Message + "' occured while performing requested operation."; Error_Panel.Visible = true; vimClient = null; return vimClient; } }
/// <summary> /// Creates an instance of the VMA proxy and establishes a connection /// </summary> /// <param name="url"></param> /// <param name="username"></param> /// <param name="password"></param> public void Connect(string url, string username, string password) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _service.Timeout = 600000; //The value can be set to some higher value also. _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, username, password, null); } _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
private void displayBasics() { service = cb.getConnection()._service; sic = cb.getConnection()._sic; perfMgr = sic.perfManager; if (cb.get_option("info").Equals("interval")) { getIntervals(perfMgr, service); } else if (cb.get_option("info").Equals("counter")) { getCounters(perfMgr, service); } else if (cb.get_option("info").Equals("host")) { ManagedObjectReference hostmor = cb.getServiceUtil().GetDecendentMoRef(null, "HostSystem", cb.get_option("hostname")); if (hostmor == null) { Console.WriteLine("Host " + cb.get_option("hostname") + " not found"); return; } getQuerySummary(perfMgr, hostmor, service); getQueryAvailable(perfMgr, hostmor, service); } else { Console.WriteLine("Invalid info argument [host|counter|interval]"); } }
/** * Initialize the necessary Managed Object References needed here */ private void initialize() { _sic = cb.getConnection()._sic; _service = cb.getConnection()._service; // Get the PropertyCollector and ScheduleManager references from ServiceContent _propCol = _sic.propertyCollector; _scheduleManager = _sic.scheduledTaskManager; }
public object Collect(string url, string username, string password) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; if ((_sic.sessionManager != null)) { _service.Login(_sic.sessionManager, username, password, null); } string apiversion = _sic.about.apiType; return(_sic); }
private async Task Connect() { _lastAction = DateTime.UtcNow; await Task.Delay(0); if (_vim != null && _vim.State == CommunicationState.Opened) { return; } //only want one client object created, so first one through wins //everyone else wait here lock (_config) { if (_vim != null && _vim.State == CommunicationState.Faulted) { _logger.LogDebug($"{_config.Url} CommunicationState is Faulted."); Disconnect().Wait(); } if (_vim == null) { try { DateTime sp = DateTime.Now; _logger.LogDebug($"Instantiating client {_config.Host}..."); VimPortTypeClient client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, _config.Url); _logger.LogDebug($"client: [{client}]"); _logger.LogDebug($"Instantiated {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogInformation($"Connecting to {_config.Url}..."); _sic = client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }).Result; _config.IsVCenter = _sic.about.apiType == "VirtualCenter"; _props = _sic.propertyCollector; _vdm = _sic.virtualDiskManager; _file = _sic.fileManager; _logger.LogDebug($"Connected {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogInformation($"logging into {_config.Host}...[{_config.User}]"); _session = client.LoginAsync(_sic.sessionManager, _config.User, _config.Password, null).Result; _logger.LogDebug($"Authenticated {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogDebug($"Initializing {_config.Host}..."); InitReferences(client).Wait(); _logger.LogDebug($"Initialized {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); _vim = client; } catch (Exception ex) { _logger.LogError(0, ex, $"Failed to connect with " + _config.Url); } } } }
private void Bind() { if (!Id.Equals(Guid.Empty)) { ServiceContent bll = new ServiceContent(); var model = bll.GetModelByJoin(Id); if (model != null) { myDataAppend.Append("<div code=\"myDataForModel\">[{\"Id\":\"" + model.Id + "\",\"ServiceItemId\":\"" + model.ServiceItemId + "\",\"ServiceItemName\":\"" + model.ServiceItemName + "\",\"Sort\":\"" + model.Sort + "\"}]</div>"); hServiceContentId.Value = model.Id.ToString(); txtNamed_ServiceContent.Value = model.Named; string pictureUrl = ""; if (!string.IsNullOrWhiteSpace(model.FileDirectory)) { pictureUrl = PictureUrlHelper.GetMPicture(model.FileDirectory, model.RandomFolder, model.FileExtension); } imgPicture_ServiceContent.Src = string.IsNullOrWhiteSpace(pictureUrl) ? "../../Images/nopic.gif" : pictureUrl; hPictureId_ServiceContent.Value = model.PictureId.ToString(); txtaDescr_ServiceContent.Value = model.Descr; txtaContent_ServiceContent.Value = model.ContentText; txtEnableStartTime_ServiceContent.Value = model.EnableStartTime == DateTime.MinValue ? "" : model.EnableStartTime.ToString("yyyy-MM-dd HH:mm:ss"); txtEnableEndTime_ServiceContent.Value = model.EnableStartTime == DateTime.MinValue ? "" : model.EnableStartTime.ToString("yyyy-MM-dd HH:mm:ss"); var li = rbtnList_ServiceContent.Items.FindByValue(model.IsDisable.ToString().ToLower()); if (li != null) { li.Selected = true; } } } }
/** * Initialize the necessary Managed Object References needed here */ private void initialize() { _sic = cb.getConnection()._sic; _service = cb.getConnection()._service; // Get the SearchIndex and ScheduleManager references from ServiceContent _searchIndex = _sic.searchIndex; _scheduleManager = _sic.scheduledTaskManager; }
public string DelServiceContent(string itemAppend) { string errorMsg = string.Empty; try { itemAppend = itemAppend.Trim(); if (string.IsNullOrEmpty(itemAppend)) { return(MessageContent.Submit_InvalidRow); } string[] items = itemAppend.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ServiceContent bll = new ServiceContent(); bll.DeleteBatch(items.ToList <object>()); } catch (Exception ex) { errorMsg = ex.Message; } if (!string.IsNullOrEmpty(errorMsg)) { return(MessageContent.AlertTitle_Ex_Error + ":" + errorMsg); } return("1"); }
private void button1_Click(object sender, EventArgs e) { try { _service = new VimService(); _service.Url = vurl; _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service.CookieContainer = new System.Net.CookieContainer(); CreateServiceRef("ServiceInstance"); _sic = _service.RetrieveServiceContent(_svcRef); _propCol = _sic.propertyCollector; _rootFolder = _sic.rootFolder; Extension ext = new Extension(); ext.key = "com.virtualizeplanet." + comboBox2.SelectedItem.ToString(); //sdsd if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, vusername, vpassword, null); ManagedObjectReference extMgrMof = _sic.extensionManager; _service.UnregisterExtension(extMgrMof, ext.key); } int c2index = comboBox2.SelectedIndex; comboBox2.Items.RemoveAt(c2index); comboBox2.Text = ""; MessageBox.Show("Done"); } catch { MessageBox.Show("Something may have gone wrong"); } }
//internal static VirtualMachineConfigInfo VmConfig{get; private set;} public bool Connect(string url, string userName, string password) { //try{ //LogEvent(this, new LogEventArgs(700, Severity.INFO, "Connecting to hypervisor "+url)); service = new VimService(); service.Url = url; service.CookieContainer = new System.Net.CookieContainer(); serviceContent = service.RetrieveServiceContent(serviceRef); propertiesCollector = serviceContent.propertyCollector; rootF = serviceContent.rootFolder; if (serviceContent.sessionManager != null) { UserSession us = service.Login(serviceContent.sessionManager, userName, password, null); if (LogEvent != null) { LogEvent(this, new LogEventArgs(0, Severity.TRIVIA, "Got session '" + us.userName + "@" + us.loginTime + "'")); } } if (LogEvent != null) { LogEvent(this, new LogEventArgs(0, Severity.DEBUG, "Instanciated connection to hypervisor " + url)); } return(true); //} //catch(Exception e){ //Logger.Append("HUBRN", Severity.ERROR, "Could not connect to hypervisor '"+url+"' : "+e.ToString()); // return false; //} }
/// <summary> /// Dump the data, register the virtual machine and do reconfig if specified. /// File greater than 500 MB is not supported. /// </summary> private void coldMigration() { _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; Boolean validated = customValidation(); if(validated) { String[] listOfDir = getSubDirectories(getLocalPath()); if(listOfDir != null && listOfDir.Length != 0) { Boolean bSize = false; // Dumping All The Data for(int i=0; i<listOfDir.Length; i++) { bSize = copyDir(listOfDir[i]); } if (bSize.ToString() == "True") { // Register The Virtual Machine Boolean regFlag = registerVirtualMachine(); //Reconfig All The Stuff Back if (regFlag) { reconfigVirtualMachine(); } } else { Console.WriteLine("Only copying files less than 500 MB is supported"); } } else { Console.WriteLine("There are no VM Directories" +" available on Specified locations"); } } else { // DO NOTHING } }
public static string getCIMSessionId(Vim25Api.ManagedObjectReference hmor1, String[] args, Cookie cookie) { AppUtil.AppUtil ecb = null; try { ecb = AppUtil.AppUtil.initialize("GetCIMSessioId" , args); ecb.connect(cookie); _service = ecb.getConnection()._service; _sic = ecb.getConnection().ServiceContent; ManagedObjectReference hmor = VersionUtil.convertManagedObjectReference(hmor1); string sessionId = _service.AcquireCimServicesTicket(hmor).sessionId; return(sessionId); } catch (Exception e) { ecb.log.LogLine("Get GetSessionID : Failed Connect"); throw e; } finally { ecb.log.LogLine("Ended GetSessionID"); ecb.log.Close(); } }
/// <summary> /// Disconnects the Connection /// </summary> public void Disconnect() { if (_service != null) { if (BeforeDisconnect != null) { BeforeDisconnect(this, new ConnectionEventArgs()); } if (_sic != null) { _service.Logout(_sic.sessionManager); } _service.Dispose(); _service = null; _sic = null; _state = ConnectionState.Disconnected; if (AfterDisconnect != null) { AfterDisconnect(this, new ConnectionEventArgs()); } } }
/// <summary> /// Creates an instance of the VMA proxy and establishes a connection /// </summary> /// <param name="url"></param> /// <param name="username"></param> /// <param name="password"></param> public void Connect(string url, string username, string password) { if (_service != null) { Disconnect(); } _service = GetVimService(url, username, password); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, username, password, null); } _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
public static string getCIMSessionId (Vim25Api.ManagedObjectReference hmor1, String[] args, Cookie cookie) { AppUtil.AppUtil ecb = null; try { ecb = AppUtil.AppUtil.initialize("GetCIMSessioId" , args); ecb.connect(cookie); _service = ecb.getConnection()._service; _sic = ecb.getConnection().ServiceContent; ManagedObjectReference hmor = VersionUtil.convertManagedObjectReference(hmor1); string sessionId = _service.AcquireCimServicesTicket(hmor).sessionId; return sessionId; } catch (Exception e) { ecb.log.LogLine("Get GetSessionID : Failed Connect"); throw e; } finally { ecb.log.LogLine("Ended GetSessionID"); ecb.log.Close(); } }
/// <summary> /// Establishe a connection using an existing cookie /// </summary> /// <param name="url">Server Url</param> /// <param name="cookie">Cookie used to connect to the server</param> public void Connect(string url, Cookie cookie) { if (_service != null) { Disconnect(); } _service = GetVimService(url); _sic = _service.RetrieveServiceContent(_svcRef); // Add the cookie to the cookie manager var cookieManager = ((IContextChannel)_service).GetProperty <IHttpCookieContainerManager>(); cookieManager.CookieContainer.SetCookies(new Uri(url), cookie.ToString()); _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
/// <summary> /// Calls the right login method based on the SAML token type (bearer or holder-of-Key) /// </summary> /// <param name="xmlToken">Token</param> public void LoginByToken(XmlElement xmlToken) { var subjectConfirmationNode = xmlToken.GetElementsByTagName(strSubjectConfirmationNode).Item(0); var subjectConfirmationMethodValue = subjectConfirmationNode.Attributes.GetNamedItem(strSubjectConfirmationMethodValueAttribute).Value; SecurityPolicyAssertion securityPolicyAssertion = null; if (subjectConfirmationMethodValue == strSubjectConfirmationMethodValueTypeHoK) { securityPolicyAssertion = GetSecurityPolicyAssertionForHokToken(xmlToken); } else if (subjectConfirmationMethodValue == strSubjectConfirmationMethodValueTypeBearer) { securityPolicyAssertion = GetSecurityPolicyAssertionForBearerToken(xmlToken); } //Setting up the security policy for the request Policy policySAML = new Policy(); policySAML.Assertions.Add(securityPolicyAssertion); // Setting policy of the service _service.SetPolicy(policySAML); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.LoginByToken(_sic.sessionManager, null); } resetService(); }
public void SSOConnect(RequestSecurityTokenResponseType token, string url) { if (_service != null) { Disconnect(); } _service = GetVimService(url, null, null, null, token.RequestedSecurityToken); _sic = _service.RetrieveServiceContent(this._svcRef); if (ServiceContent.sessionManager != null) { var userSession = _service.LoginByToken(ServiceContent.sessionManager, null); VimUserSession = userSession; } _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { await Task.Yield(); while (!cancellationToken.IsCancellationRequested) { try { _options = _optionsMonitor.CurrentValue; _client = _connectionService.GetClient(); _sic = _connectionService.GetServiceContent(); _props = _connectionService.GetProps(); _tasksPending = false; using (var scope = _serviceProvider.CreateScope()) { _dbContext = scope.ServiceProvider.GetRequiredService <VmContext>(); await processTasks(); } } catch (Exception ex) { _logger.LogError(ex, "Exception in TaskService"); } var intervalMilliseconds = _tasksPending ? _options.ReCheckTaskProgressIntervalMilliseconds : _options.CheckTaskProgressIntervalMilliseconds; _taskServiceHealthCheck.CompletedRun(); await _resetEvent.WaitAsync(new TimeSpan(0, 0, 0, 0, intervalMilliseconds)); } }
public PropertyManager(SvcConnection connection, ServiceContent context) { _context = context; _connection = connection; WaitForUpdatesDone += new AsyncCallback(PropertyManager_WaitForUpdatesDone); _filterUpdates = new Dictionary<String, PropertyFilterUpdateHandler>(); _isListening = false; }
public void Disconnect() { _logger.LogInformation($"Disconnect()"); _client.Dispose(); _client = null; _sic = null; _session = null; }
public VMWareVirtualMachine(ManagedObjectReference vmmor, AppUtil.AppUtil cb, string vmId) { this.vmmor = vmmor; this.cb = cb; this.vmId = vmId; this._service = cb.getConnection()._service; this._sic = cb.getConnection()._sic; }
private async Task <UserSession> ConnectToSession(VimPortTypeClient client, ServiceContent sic) { _logger.LogInformation($"Connect(): logging into {_options.Host}...[{_options.Username}]"); var session = await client.LoginAsync(sic.sessionManager, _options.Username, _options.Password, null); _logger.LogInformation($"Connect(): Session created."); return(session); }
/// <summary> /// Disconnects this instance. /// </summary> public void Disconnect() { if (_serviceContent != null) { _vimService.Logout(_serviceContent.sessionManager); _serviceContent = null; } }
private void initialize() { _sic = cb.getConnection()._sic; _service = cb.getConnection()._service; // The PropertyCollector and EventManager References are present // in the ServiceInstanceContent _propCol = _sic.propertyCollector; _eventManager = _sic.eventManager; }
public PropertyManager(SvcConnection connection, ServiceContent context) { _context = context; _connection = connection; WaitForUpdatesDone += new AsyncCallback(PropertyManager_WaitForUpdatesDone); _filterUpdates = new Dictionary <String, PropertyFilterUpdateHandler>(); _isListening = false; }
public void displayNewProperties() { _service = ecb.getConnection().Service; _sic = ecb.getConnection().ServiceContent; String vmName = ecb.get_option("vmname"); ManagedObjectReference vmmor = ecb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); if (vmmor != null) { ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url")); Object[] vmProps = getProperties(vmmor, new String[] { "name" }); String serverName = (String)vmProps[0]; Console.WriteLine("Virtual Machine Name " + serverName); vmProps = getProperties(vmmor, new String[] { "config.uuid" }); String uuid = (String)vmProps[0]; Console.WriteLine("Config UUID " + uuid); vmProps = getProperties(vmmor, new String[] { "config.guestId" }); String guestId = (String)vmProps[0]; Console.WriteLine("Guest Id " + guestId); if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { vmProps = getProperties(vmmor, new String[] { "name" }); Boolean bootOptionsSupported = (Boolean)getObjectProperty(vmmor, "capability.bootOptionsSupported"); Console.WriteLine("Boot Options Supported " + bootOptionsSupported); Boolean diskSharesSupported = (Boolean)getObjectProperty(vmmor, "capability.diskSharesSupported"); Console.WriteLine("Disk Shares Supported " + diskSharesSupported); Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0"); Console.WriteLine("Is API Supported " + flag); if (flag) { Console.WriteLine("\nProperties added in vSphere API 4.0\n"); Boolean changeTrackingSupported = (Boolean)getObjectProperty(vmmor, "capability.changeTrackingSupported"); Console.WriteLine("Change Tracking Supported " + changeTrackingSupported); Boolean recordReplaySupported = (Boolean)getObjectProperty(vmmor, "capability.recordReplaySupported"); Console.WriteLine("Record Replay Supported " + recordReplaySupported); VirtualMachineFaultToleranceState faultToleranceState = (VirtualMachineFaultToleranceState)getObjectProperty(vmmor, "runtime.faultToleranceState"); Console.WriteLine("Fault Tolerance State " + faultToleranceState); } } } else { Console.WriteLine("Virtal Machine Not Found"); } }
private void cloneVM() { _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; String cloneName = cb.get_option("CloneName"); String vmPath = cb.get_option("vmPath"); String datacenterName= cb.get_option("DatacenterName"); // Find the Datacenter reference by using findByInventoryPath(). ManagedObjectReference datacenterRef = _service.FindByInventoryPath(_sic.searchIndex, datacenterName); if (datacenterRef == null) { Console.WriteLine("The specified datacenter is not found"); return; } // Find the virtual machine folder for this datacenter. ManagedObjectReference vmFolderRef = (ManagedObjectReference)cb.getServiceUtil().GetMoRefProp(datacenterRef, "vmFolder"); if (vmFolderRef == null) { Console.WriteLine("The virtual machine is not found"); return; } ManagedObjectReference vmRef = _service.FindByInventoryPath(_sic.searchIndex, vmPath); if (vmRef == null) { Console.WriteLine("The virtual machine is not found"); return; } VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec(); cloneSpec.location=relocSpec; cloneSpec.powerOn=false; cloneSpec.template=false; String clonedName = cloneName; Console.WriteLine("Launching clone task to create a clone: " + clonedName); try { ManagedObjectReference cloneTask = _service.CloneVM_Task(vmRef, vmFolderRef, clonedName, cloneSpec); String status = cb.getServiceUtil().WaitForTask(cloneTask); if(status.Equals("failure")) { Console.WriteLine("Failure -: Virtual Machine cannot be cloned"); } if (status.Equals("sucess")) { Console.WriteLine("Virtual Machine Cloned successfully."); } else{ Console.WriteLine("Virtual Machine Cloned cannot be cloned"); } } catch(Exception e) { } }
public async Task Disconnect() { _logger.LogDebug($"Disconnecting from {this.Name}"); await Task.Delay(500); _vim.Dispose(); _vim = null; _sic = null; _session = null; }
public static DalContent ToDalContent(this ServiceContent content) { return(new DalContent { ID = content.ID, BookID = content.BookID, UserID = content.UserID, Text = content.Text }); }
public static ContentModel GetContentModel(ServiceContent content) { UserShortModel user = manager.userService.GetUserProfile(content.UserID)?.ToUserShortModel() ?? new ServiceUserProfile() { ID = content.UserID }.ToUserShortModel(); return(content.ToContentModel(user, Book.GetBookShortModel(content.BookID, content.UserID))); }
public static ContentModel ToContentModel(this ServiceContent content, UserShortModel user, BookShortModel book) { return(new ContentModel { Book = book, ID = content.ID, Text = content.Text, User = user }); }
private void Disconnect() { // Disconnect from the service: if (vim_svc != null) { vim_svc.Logout(vim_svc_content.sessionManager); vim_svc.Dispose(); vim_svc = null; vim_svc_content = null; } }
public void Disconnect() { if (_service != null) { _service.Logout(_sic.sessionManager); _service.Dispose(); _service = null; _sic = null; } }
private void DoConnect(String url, String hostName) { System.Net.ServicePointManager.CertificatePolicy = new CertPolicy(); _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; _service = new VimService(); _service.Url = url; _service.Timeout = 600000; //The value can be set to some higher value also. _service.CookieContainer = new System.Net.CookieContainer(); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { Boolean flag = true; SSPIClientCredential clientCred = new SSPIClientCredential(SSPIClientCredential.Package.Negotiate); SSPIClientContext clientContext = new SSPIClientContext(clientCred, "", SSPIClientContext.ContextAttributeFlags.None); //ManagedObjectReference hostmor = _service.FindByIp(_sic.searchIndex, null, // hostName,false); while (flag) { try { _service.LoginBySSPI(_sic.sessionManager, Convert.ToBase64String(clientContext.Token), "en"); flag = false; } catch (Exception e) { SoapException se = (SoapException)e; clientContext.Initialize(Convert.FromBase64String(se.Detail.InnerText)); try { Console.WriteLine("Time " + _service.CurrentTime(_svcRef)); flag = false; } catch (Exception ex) { flag = true; } } } //HostServiceTicket cimTicket = _service.AcquireCimServicesTicket(hostmor); //String sessionId = cimTicket.sessionId; //GetComputeSystem(sessionId, hostName); } }
public void PowerDownHost(String[] args) { _service = cb.getConnection().Service; _sic = cb.getConnection().ServiceContent; String hostname = cb.get_option("hostname"); ManagedObjectReference hmor = cb.getServiceUtil().GetDecendentMoRef(null, "HostSystem", hostname); if (hmor != null) { if (cb.get_option("operation").Equals("reboot")) { ManagedObjectReference taskmor = _service.RebootHost_Task(hmor, true); String result = cb.getServiceUtil().WaitForTask(taskmor); if (result.Equals("sucess")) { Console.WriteLine("Operation reboot host" + " completed sucessfully"); } } else if (cb.get_option("operation").Equals("shutdown")) { ManagedObjectReference taskmor = _service.ShutdownHost_Task(hmor, true); String result = cb.getServiceUtil().WaitForTask(taskmor); if (result.Equals("sucess")) { Console.WriteLine("Operation shutdown host" + " completed sucessfully"); } } else if (cb.get_option("operation").Equals("powerdowntostandby")) { ManagedObjectReference taskmor = _service. PowerDownHostToStandBy_Task(hmor, 120, false, true); String result = cb.getServiceUtil().WaitForTask(taskmor); if (result.Equals("sucess")) { Console.WriteLine("Operation powerDownHostToStandBy" + " completed sucessfully"); } } } else { Console.WriteLine("Host " + cb.get_option("hostname") + " not found"); } }
public static void powerDownHost(VimApi.ManagedObjectReference hmor, String[] args, ArrayList apiVersions, Cookie cookie) { ExtendedAppUtil ecb = null; ecb = ExtendedAppUtil.initialize("PowerDownHostToStandBy" , HostPowerOps.constructOptions() ,args); ecb.connect(cookie); _service = ecb.getServiceConnectionV25().Service; _sic = ecb.getServiceConnectionV25().ServiceContent; // Convert the vim managed object to vim25 managed object ManagedObjectReference hmor1 = VersionUtil.convertManagedObjectReference(hmor); ManagedObjectReference taskmor = _service.PowerDownHostToStandBy_Task(hmor1,120,false,true); String result = ecb.getServiceUtilV25().WaitForTask(taskmor); if(result.Equals("sucess")) { Console.WriteLine("Operation powerDownHostToStandBy" +" completed sucessfully"); } }
public void RecordSessionOfVM() { try { _service = ecb.getConnection().Service; _sic = ecb.getConnection().ServiceContent; ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url")); ManagedObjectReference vmmor = ecb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", ecb.get_option("vmname")); if (vmmor == null) { Console.WriteLine("Unable to find VirtualMachine named : " + ecb.get_option("vmname") + " in Inventory"); } if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0"); if (flag) { if (ecb.get_option("snapshotname") == null || ecb.get_option("description") == null) { Console.WriteLine("snapshotname and description arguments are " + "mandatory for recording session feature"); return; } VirtualMachineFlagInfo flagInfo = new VirtualMachineFlagInfo(); flagInfo.recordReplayEnabled = true; flagInfo.recordReplayEnabledSpecified = true; VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec(); configSpec.flags = flagInfo; _service.ReconfigVM_TaskAsync(vmmor, configSpec); _service.StartRecording_TaskAsync(vmmor, ecb.get_option("snapshotname"), ecb.get_option("description")); _service.StopRecording_TaskAsync(vmmor); Console.WriteLine("Session recorded successfully"); } else { VirtualMachineSnapshotTree[] tree = (VirtualMachineSnapshotTree[])getObjectProperty(vmmor, "snapshot.rootSnapshotList"); if (tree != null && tree.Length != 0) { ManagedObjectReference taskMor = _service.RemoveAllSnapshots_Task(vmmor, true, false); object[] result = ecb.getServiceUtil().WaitForValues(taskMor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); if (result[0].Equals(TaskInfoState.success)) { Console.WriteLine("Removed all the snapshot successfully"); } } else { Console.WriteLine("No snapshot found for this virtual machine"); } } } else { VirtualMachineSnapshotTree[] tree = (VirtualMachineSnapshotTree[])getObjectProperty(vmmor, "snapshot.rootSnapshotList"); if (tree != null && tree.Length != 0) { ManagedObjectReference taskMor = _service.RemoveAllSnapshots_Task(vmmor, true, false); object[] result = ecb.getServiceUtil().WaitForValues(taskMor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); if (result[0].Equals(TaskInfoState.success)) { Console.WriteLine("Removed all the snapshot successfully"); } } else { Console.WriteLine("No snapshot found for this virtual machine"); } } } catch (Exception e) { ecb.log.LogLine("RecordSession : Failed Connect"); throw e; } finally { ecb.log.LogLine("Ended RecordSession"); ecb.log.Close(); } }
public void deploy(VM guest) { cb = AppUtil.AppUtil.initialize("VMDeploy", this.connectString); cb.connect(); /************Start Deploy Code*****************/ _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; // ManagedObjectReferences ManagedObjectReference datacenterRef; ManagedObjectReference vmFolderRef; ManagedObjectReference vmRef; ManagedObjectReference hfmor; // hostFolder reference ArrayList crmors; // ArrayList of ComputeResource references ManagedObjectReference hostmor; ManagedObjectReference crmor = null; // ComputeResource reference ManagedObjectReference resourcePool; // Find the Datacenter reference by using findByInventoryPath(). datacenterRef = _service.FindByInventoryPath(_sic.searchIndex, this.dataCenter); if (datacenterRef == null) { Console.WriteLine("The specified datacenter is not found"); return; } // Find the virtual machine folder for this datacenter. vmFolderRef = (ManagedObjectReference)cb.getServiceUtil().GetMoRefProp(datacenterRef, "vmFolder"); if (vmFolderRef == null) { Console.WriteLine("The virtual machine is not found"); return; } vmRef = _service.FindByInventoryPath(_sic.searchIndex, guest.getVmPath()); if (vmRef == null) { Console.WriteLine("The virtual machine is not found"); return; } // Code for obtaining managed object reference to resource root hfmor = cb.getServiceUtil().GetMoRefProp(datacenterRef, "hostFolder"); crmors = cb.getServiceUtil().GetDecendentMoRefs(hfmor, "ComputeResource", null); if (this.hostName != null) { hostmor = cb.getServiceUtil().GetDecendentMoRef(hfmor, "HostSystem", this.hostName); if (hostmor == null) { Console.WriteLine("Host " + this.hostName + " not found"); return; } } else { hostmor = cb.getServiceUtil().GetFirstDecendentMoRef(datacenterRef, "HostSystem"); } hostName = (String)cb.getServiceUtil().GetDynamicProperty(hostmor, "name"); for (int i = 0; i < crmors.Count; i++) { ManagedObjectReference[] hrmors = (ManagedObjectReference[])cb.getServiceUtil().GetDynamicProperty((ManagedObjectReference)crmors[i], "host"); if (hrmors != null && hrmors.Length > 0) { for (int j = 0; j < hrmors.Length; j++) { String hname = (String)cb.getServiceUtil().GetDynamicProperty(hrmors[j], "name"); if (hname.Equals(this.hostName)) { crmor = (ManagedObjectReference)crmors[i]; i = crmors.Count + 1; j = hrmors.Length + 1; } } } } if (crmor == null) { Console.WriteLine("No Compute Resource Found On Specified Host"); return; } resourcePool = cb.getServiceUtil().GetMoRefProp(crmor, "resourcePool"); /***********************************/ /*Setup cloning sysprep preferences*/ /***********************************/ VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec(); // Set resource pool for relocspec(compulsory since deploying template) relocSpec.pool = resourcePool; cloneSpec.location = relocSpec; cloneSpec.powerOn = true; //Specifies whether or not the new VirtualMachine should be powered on after creation. As part of a customization, this flag is normally set to true, since the first power-on operation completes the customization process. This flag is ignored if a template is being created. cloneSpec.template = false; //Specifies whether or not the new virtual machine should be marked as a template. // Customization CustomizationSpec custSpec = new CustomizationSpec(); // Make NIC settings CustomizationAdapterMapping[] custAdapter = new CustomizationAdapterMapping[1]; custAdapter[0] = new CustomizationAdapterMapping(); CustomizationIPSettings custIPSettings = new CustomizationIPSettings(); CustomizationDhcpIpGenerator custDhcp = new CustomizationDhcpIpGenerator(); custIPSettings.ip = custDhcp; custAdapter[0].adapter = custIPSettings; // Set NIC settings custSpec.nicSettingMap = custAdapter; // Make DNS entry CustomizationGlobalIPSettings custIP = new CustomizationGlobalIPSettings(); custIP.dnsServerList = guest.getDnsList(); ; // Set DNS entry custSpec.globalIPSettings = custIP; // Make Sysprep entries CustomizationSysprep custPrep = new CustomizationSysprep(); //An object representation of a Windows sysprep.inf answer file. The sysprep type encloses all the individual keys listed in a sysprep.inf file // Make guiRunOnce entries(to change autologon settings to login to domain) //CustomizationGuiRunOnce custGuiRunOnce = new CustomizationGuiRunOnce(); //string deleteKey = "reg delete \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\" /v \"DefaultDomainName\" /f"; //string addKey = "reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\" /v \"DefaultDomainName\" /t REG_SZ /d " + this.joinDomain; //string shutdownKey = "shutdown -r -t 00 -c \"Rebooting computer\""; //custGuiRunOnce.commandList = new string[] { deleteKey, addKey, shutdownKey }; // Set guiRunOnce //custPrep.guiRunOnce = custGuiRunOnce; // Make guiUnattended settings CustomizationGuiUnattended custGui = new CustomizationGuiUnattended(); //The GuiUnattended type maps to the GuiUnattended key in the sysprep.inf answer file //The GuiUnattended type maps to the GuiUnattended key in the sysprep.inf answer file if (Int32.Parse(guest.getAutoLogonCount()) == 0) { custGui.autoLogon = false; } else { custGui.autoLogon = true; custGui.autoLogonCount = Int16.Parse(guest.getAutoLogonCount()); //If the AutoLogon flag is set, then the AutoLogonCount property specifies the number of times the machine should automatically log on as Administrator } CustomizationPassword custWorkPass = new CustomizationPassword(); if (guest.getWorkGroupPassword() != null) { custWorkPass.plainText = true; //Flag to specify whether or not the password is in plain text, rather than encrypted. custWorkPass.value = guest.getWorkGroupPassword(); custGui.password = custWorkPass; } custGui.timeZone = 190; //IST The time zone for the new virtual machine. Numbers correspond to time zones listed in sysprep documentation at in Microsoft Technet. Taken from unattend.txt // Set guiUnattend settings custPrep.guiUnattended = custGui; // Make identification settings CustomizationIdentification custId = new CustomizationIdentification(); custId.domainAdmin = guest.getDomainAdmin(); CustomizationPassword custPass = new CustomizationPassword(); custPass.plainText = true; //Flag to specify whether or not the password is in plain text, rather than encrypted. custPass.value = guest.getDomainPassword(); custId.domainAdminPassword = custPass; custId.joinDomain = guest.getJoinDomain(); // Set identification settings custPrep.identification = custId; // Make userData settings CustomizationUserData custUserData = new CustomizationUserData(); CustomizationFixedName custName = new CustomizationFixedName(); custName.name = guest.getName(); custUserData.computerName = custName; custUserData.fullName = "ePO"; custUserData.orgName = "McAfee"; if (guest.getProductId() != null) { custUserData.productId = guest.getProductId(); } // Set userData settings custPrep.userData = custUserData; // Set sysprep custSpec.identity = custPrep; // clonespec customization cloneSpec.customization = custSpec; // clone power on cloneSpec.powerOn = true; String clonedName = guest.getName(); Console.WriteLine("Launching clone task to create a clone: " + clonedName); try { ManagedObjectReference cloneTask = _service.CloneVM_Task(vmRef, vmFolderRef, clonedName, cloneSpec); String status = cb.getServiceUtil().WaitForTask(cloneTask); if (status.Equals("failure")) { Console.WriteLine("Failure -: Virtual Machine cannot be cloned"); } if (status.Equals("sucess")) { Console.WriteLine("Virtual Machine Cloned successfully."); } else { Console.WriteLine("Virtual Machine Cloned cannot be cloned"); } } catch (Exception e) { } /************End Deploy Code*******************/ cb.disConnect(); }
public void SSOConnect(XmlElement token, string url) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _service.Timeout = 600000; //The value can be set to some higher value also. _service.CookieContainer = new System.Net.CookieContainer(); //... //When this property is set to true, client requests that use the POST method //expect to receive a 100-Continue response from the server to indicate that //the client should send the data to be posted. This mechanism allows clients //to avoid sending large amounts of data over the network when the server, //based on the request headers, intends to reject the request ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; var customSecurityAssertion = new CustomSecurityAssertionBearer(); customSecurityAssertion.BinaryToken = token; //Setting up the security policy for the request Policy policySAML = new Policy(); policySAML.Assertions.Add(customSecurityAssertion); // Setting policy of the service _service.SetPolicy(policySAML); _sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.LoginByToken(_sic.sessionManager, null); } _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
/// <summary> /// The main entry point for the application. /// </summary> public static void Main(String[] args) { try { PropertyCollector app = new PropertyCollector(); cb = AppUtil.AppUtil.initialize("PropertyCollector", PropertyCollector.constructOptions(), args); cb.connect(); ManagedObjectReference sic = cb.getConnection().ServiceRef; _sic = cb.getConnection()._sic; _service = cb.getConnection()._service; String dcName = cb.get_option("dcName"); String vmDnsName = cb.get_option("vmDnsName"); ObjectContent[] ocs = null; ManagedObjectReference dcMoRef = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", dcName); if (dcMoRef == null) { Console.WriteLine("Datacenter not found"); } else { ManagedObjectReference vmMoRef = _service.FindByDnsName(_sic.searchIndex, dcMoRef, vmDnsName, true); if (vmMoRef == null) { Console.WriteLine("The virtual machine with DNS '" + vmDnsName + "' not found "); } else { // Retrieve name and powerState from a Virtual Machine Object[] properties = getProperties(vmMoRef, new String[] { "name", "runtime.powerState" }); String vmName = (String)properties[0]; VirtualMachinePowerState vmState = (VirtualMachinePowerState)properties[1]; if (vmName != null && vmState != null) { Console.WriteLine("The VM with DNS name \'" + vmDnsName + "\' is named \'" + vmName + "\' and is " + vmState.ToString()); } ocs = getDatacenters(); printObjectContent(ocs, "All Datacenters"); // Find all the VMs in the Datacenter ocs = getVMs(dcMoRef); printObjectContent(ocs, "All VMs in the Datacenter: " + dcName); //Find all the Hosts in the Datacenter ocs = getHosts(dcMoRef); printObjectContent(ocs, "All Hosts in the Datacenter: " + dcName); // Display summary information about a VM ocs = getVMInfo(vmMoRef); printVmInfo(ocs); // Display all of inventory ocs = getInventory(); printInventoryTree(ocs); ocs = getNetworkInfo(dcMoRef); printNetworkInfo(ocs); cb.disConnect(); Console.WriteLine("Press any key to exit:"); Console.Read(); } } } catch (SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("DuplicateNameFault")) { Console.WriteLine("Managed Entity with the name already exists"); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault")) { Console.WriteLine("Specification is invalid"); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidNameFault")) { Console.WriteLine("Managed Entity Name is empty or too long"); } else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault")) { Console.WriteLine(e.Message.ToString() + "Either parent name or item name is invalid"); } else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault")) { Console.WriteLine(e.Message.ToString() + " " + "The Operation is not supported on this object"); } else { Console.WriteLine(e.Message.ToString() + " " + "The Operation is not supported on this object"); } } Console.Read(); }
public void GetVirtualDiskFilesForHost() { try { _service = ecb.getConnection().Service; _sic = ecb.getConnection().ServiceContent; ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url")); ManagedObjectReference hmor = _service.FindByIp(ecb.getConnection().ServiceContent.searchIndex, null, ecb.get_option("hostip"), false); if (hmor == null) { Console.WriteLine("Unable to find host with IP : " + ecb.get_option("hostip") + " in Inventory"); } else { if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { Object[] datastores = getProperties(hmor, new String[] { "datastore" }); Console.WriteLine("Searching The Datastores"); ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[]; foreach (ManagedObjectReference dstore in dstoreArr) { ManagedObjectReference dsBrowser = ecb.getServiceUtil().GetMoRefProp(dstore, "browser"); ObjectContent[] objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" }); DatastoreSummary ds = objary[0].propSet[0].val as DatastoreSummary; String dsName = ds.name; Console.WriteLine(""); Console.WriteLine("Searching The Datastore " + dsName); VmDiskFileQueryFilter vdiskFilter = new VmDiskFileQueryFilter(); String[] type = { "VirtualIDEController" }; vdiskFilter.controllerType = type; Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0"); if (flag) { vdiskFilter.thin = true; } VmDiskFileQuery fQuery = new VmDiskFileQuery(); fQuery.filter = vdiskFilter; HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec(); FileQuery[] arr = { fQuery }; searchSpec.query = arr; //searchSpec.setMatchPattern(matchPattern); ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec); object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); // Wait till the task completes. if (result[0].Equals(TaskInfoState.success)) { ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" }); TaskInfo tInfo = (TaskInfo)objTaskInfo[0].propSet[0].val; ; HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result; int len = searchResult.Length; for (int j = 0; j < len; j++) { HostDatastoreBrowserSearchResults sres = searchResult[j]; FileInfo[] fileArray = sres.file; if (fileArray != null) { for (int z = 0; z < fileArray.Length; z++) { Console.WriteLine("Virtual Disks Files " + fileArray[z].path); } } else { Console.WriteLine("No Thin-provisioned Virtual Disks Files found"); } } } else { Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully"); } } } else { Object[] datastores = getProperties(hmor, new String[] { "datastore" }); Console.WriteLine("Searching The Datastores"); ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[]; foreach (ManagedObjectReference dstore in dstoreArr) { ManagedObjectReference dsBrowser = (ManagedObjectReference) ecb.getServiceUtil().GetMoRefProp(dstore, "browser"); ObjectContent[] objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" }); DatastoreSummary ds = objary[0].propSet[0].val as DatastoreSummary; String dsName = ds.name; Console.WriteLine(""); Console.WriteLine("Searching The Datastore " + dsName); HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec(); ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec); object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); // Wait till the task completes. if (result[0].Equals(TaskInfoState.success)) { ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" }); TaskInfo tInfo = (TaskInfo)objTaskInfo[0].propSet[0].val; ; HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result; int len = searchResult.Length; for (int j = 0; j < len; j++) { HostDatastoreBrowserSearchResults sres = searchResult[j]; FileInfo[] fileArray = sres.file; for (int z = 0; z < fileArray.Length; z++) { Console.WriteLine("Virtual Disks Files " + fileArray[z].path); } } } else { Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully"); } } } } } catch (Exception e) { ecb.log.LogLine("VirtualDiskFiles : Failed Connect"); throw e; } finally { ecb.log.LogLine("Ended VirtualDiskFiles"); ecb.log.Close(); } }
public static void Main(String[] args) { string sHost = ""; int totalCpuUsage = 0; int totalMemUsage = 0; string content=""; FileStream fs = null; if(!File.Exists("../../Output.txt")) { fs = new FileStream("../../Output.txt",FileMode.Create); } else { fs = new FileStream("../../Output.txt",FileMode.Append); } try { PropertyCollector app = new PropertyCollector(); cb = AppUtil.AppUtil.initialize("PropertyCollector", PropertyCollector.constructOptions(), args); cb.connect(); ManagedObjectReference sic = cb.getConnection().ServiceRef; _sic = cb.getConnection()._sic; _service = cb.getConnection()._service; String dcName = cb.get_option("dcName"); String vmName = cb.get_option("vmName"); ObjectContent[] ocs = null; ManagedObjectReference dcMoRef = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", dcName); if (dcMoRef == null) { Console.WriteLine("Datacenter not found"); } else { ManagedObjectReference vmMoRef = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); if (vmMoRef == null) { Console.WriteLine("The virtual machine with DNS '" + vmName + "' not found "); } else { // Display summary information about a VM while(true) { for (int times = 0; times < 12; times++) { ocs = getVMInfo(vmMoRef); printVmInfo(ocs, ref totalCpuUsage, ref totalMemUsage, ref content, fs, ref sHost); Console.WriteLine("\n The system will halt for 15 seconds \n"); Thread.Sleep(15 * 1000); } if ((double)(totalCpuUsage / 120) > 50 || (double)(totalMemUsage) / 12 > 300) { try { string vmname = "jwang74_2"; string pool = "jwang74"; string[] tHostArray = { "128.230.96.39", "128.230.96.41", "128.230.96.39", "128.230.96.40", "128.230.96.111" }; string tHost = ""; do { Random a = new Random(); int i = a.Next(0, 5); tHost = tHostArray[i]; } while (tHost == sHost); migrateVM(vmname, pool, tHost, sHost); Console.WriteLine("Do you want to continue: Y/N"); string con = Console.ReadLine(); if (con.Equals("Y") || con.Equals("y")) { continue; } else { break; } } catch (Exception) { } Console.WriteLine("Press any key to exit: "); Console.Read(); } Console.WriteLine("Do you want to continue: Y/N"); string condition = Console.ReadLine(); if (condition.Equals("Y") || condition.Equals("y")) { continue; } else { break; } } cb.disConnect(); Console.WriteLine("Press any key to exit:"); Console.Read(); } } } catch (SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("DuplicateNameFault")) { Console.WriteLine("Managed Entity with the name already exists"); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault")) { Console.WriteLine("Specification is invalid"); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidNameFault")) { Console.WriteLine("Managed Entity Name is empty or too long"); } else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault")) { Console.WriteLine(e.Message.ToString() + "Either parent name or item name is invalid"); } else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault")) { Console.WriteLine(e.Message.ToString() + " " + "The Operation is not supported on this object"); } else { Console.WriteLine(e.Message.ToString() + " " + "The Operation is not supported on this object"); } } Console.Read(); fs.Close(); }
/// <summary> /// Disconnects the Connection /// </summary> public void Disconnect() { if (_service != null) { if (BeforeDisconnect != null) { BeforeDisconnect(this, new ConnectionEventArgs()); } if (_sic != null) _service.Logout(_sic.sessionManager); _service.Dispose(); _service = null; _sic = null; _state = ConnectionState.Disconnected; if (AfterDisconnect != null) { AfterDisconnect(this, new ConnectionEventArgs()); } } }
public void LoadSession(String fileName, String urlString) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = urlString; _service.Timeout = 600000; _service.CookieContainer = new System.Net.CookieContainer(); BinaryFormatter bf = new BinaryFormatter(); Stream s = File.Open(fileName, FileMode.Open); Cookie c = bf.Deserialize(s) as Cookie; s.Close(); _service.CookieContainer.Add(c); _sic = _service.RetrieveServiceContent(_svcRef); _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
/** Excercise the SearchIndex API * * @param args Usage is: * <url> <user> <password> <Datacenter Name> <A VM DNS Name> * <A Host DNS Name> <A VM Inventory Path> */ public static void Main(String[] args) { try { SearchIndex app = new SearchIndex(); cb = AppUtil.AppUtil.initialize("SearchIndex" ,SearchIndex.constructOptions() ,args); cb.connect(); String dcName = cb.get_option("dcName"); String vmDnsName = cb.get_option("vmDnsName"); String hostDnsName =cb.get_option("hostDnsName"); String vmPath = cb.get_option("vmPath"); String vmIP = cb.get_option("vmIP"); content = cb.getConnection()._sic; service = cb.getConnection()._service; // Find the Datacenter by using findChild() ManagedObjectReference dcMoRef = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", dcName); if (dcMoRef !=null){ Console.WriteLine("Found Datacenter with name: " +dcName+", MoRef: " + dcMoRef.Value); }else{ Console.WriteLine("Datacenter not Found with name: "+dcName); } if (vmDnsName != null){ ManagedObjectReference vmMoRef = service.FindByDnsName(content.searchIndex, dcMoRef, vmDnsName, true); if (vmMoRef !=null){ Console.WriteLine("Found VirtualMachine with DNS name: "+ vmDnsName+", MoRef: " + vmMoRef.Value); } else{ Console.WriteLine("VirtualMachine not Found with DNS name: " + vmDnsName); } } if (vmPath != null){ ManagedObjectReference vmMoRef = service.FindByInventoryPath( content.searchIndex, vmPath); if (vmMoRef !=null) { Console.WriteLine("Found VirtualMachine with Path: "+ vmPath+", MoRef: " + vmMoRef.Value); } else{ Console.WriteLine("VirtualMachine not found with vmPath "+ "address: "+ vmPath); } } if (vmIP != null){ ManagedObjectReference vmMoRef = service.FindByIp(content.searchIndex, dcMoRef, vmIP, true); if (vmMoRef !=null){ Console.WriteLine("Found VirtualMachine with IP "+ "address "+ vmIP + ", MoRef: " + vmMoRef.Value); }else{ Console.WriteLine("VirtualMachine not found with IP "+ "address: "+vmIP); } } if (hostDnsName != null) { ManagedObjectReference hostMoRef = service.FindByDnsName(content.searchIndex, null, hostDnsName, false); if (hostMoRef !=null) { Console.WriteLine("Found HostSystem with DNS name "+ hostDnsName+", MoRef: " + hostMoRef.Value); } else{ Console.WriteLine("HostSystem not Found with DNS name:"+ hostDnsName); } } cb.disConnect(); Console.WriteLine("Press enter to exit: "); Console.Read(); } catch(SoapException e) { } }
public void queryMemoryOverhead() { _service = ecb.getConnection().Service; _sic = ecb.getConnection().ServiceContent; ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url")); String hostname = ecb.get_option("hostname"); ManagedObjectReference hmor = ecb.getServiceUtil().GetDecendentMoRef(null, "HostSystem", hostname); if (hmor != null) { if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { VirtualMachineConfigInfo vmConfigInfo = new VirtualMachineConfigInfo(); vmConfigInfo.changeVersion = "1"; DateTime dt = ecb.getConnection().Service.CurrentTime(ecb.getConnection().ServiceRef); vmConfigInfo.modified = dt; VirtualMachineDefaultPowerOpInfo defaultInfo = new VirtualMachineDefaultPowerOpInfo(); vmConfigInfo.defaultPowerOps=defaultInfo; VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); vmConfigInfo.files=fileInfo; VirtualMachineFlagInfo flagInfo = new VirtualMachineFlagInfo(); vmConfigInfo.flags=flagInfo; vmConfigInfo.guestFullName="Full Name"; vmConfigInfo.guestId="Id"; VirtualHardware vhardware = new VirtualHardware(); vhardware.memoryMB=int.Parse(ecb.get_option("memorysize")); vhardware.numCPU=int.Parse(ecb.get_option("cpucount")); vmConfigInfo.hardware=vhardware; // Not Required For Computing The Overhead vmConfigInfo.name="OnlyFoeInfo"; vmConfigInfo.uuid="12345678-abcd-1234-cdef-123456789abc"; vmConfigInfo.version="First"; vmConfigInfo.template=false; vmConfigInfo.alternateGuestName="Alternate"; long overhead = ecb._connection._service.QueryMemoryOverheadEx( hmor,vmConfigInfo); Console.WriteLine("Using queryMemoryOverheadEx API using vmReconfigInfo"); Console.WriteLine("Memory overhead necessary to " + "poweron a virtual machine with memory " + ecb.get_option("memorysize") + " MB and cpu count " + ecb.get_option("cpucount") + " -: " + overhead + " bytes"); } else { long overhead = ecb._connection._service.QueryMemoryOverhead(hmor, long.Parse(ecb.get_option("memorysize")), 0, false, int.Parse(ecb.get_option("cpucount")) ); Console.WriteLine("Using queryMemoryOverhead API " + "using CPU count and Memory Size"); Console.WriteLine("Memory overhead necessary to " + "poweron a virtual machine with memory " + ecb.get_option("memorysize") + " MB and cpu count " + ecb.get_option("cpucount") + " -: " + overhead + " bytes"); } } else { Console.WriteLine("Host " + ecb.get_option("hostname") + " not found"); } }
private void displayProperties(String[] args) { _service = cb.getConnection().Service; _sic = cb.getConnection().ServiceContent; String hostName = cb.get_option("hostname"); ManagedObjectReference hmor = _service.FindByDnsName(_sic.searchIndex, null, hostName, false); if (hmor != null) { ArrayList supportedVersions = VersionUtil.getSupportedVersions(cb.get_option("url")); if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { _service = cb.getConnection().Service; _sic = cb.getConnection().ServiceContent; Object[] vmProps = getProperties(hmor, new String[] { "name" }); String serverName = (String)vmProps[0]; Console.WriteLine("Server Name " + serverName); HostRuntimeInfo runtimeInfo = (HostRuntimeInfo)getObjectProperty(hmor, "runtime"); DateTime dt = runtimeInfo.bootTime; Console.WriteLine("Boot Time " + dt.ToString()); String powerState = runtimeInfo.powerState.ToString(); Console.WriteLine("Power State " + powerState); HostConfigInfo configInfo = (HostConfigInfo)getObjectProperty(hmor, "config"); String timeZone = configInfo.dateTimeInfo.timeZone.key; Console.WriteLine("Time Zone " + timeZone); Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0"); if (flag) { Console.WriteLine("\nProperties added in 4.0 VI API\n"); Object objFlag = getObjectProperty(hmor, "capability.ipmiSupported"); if (objFlag != null) { Boolean infoFlag = (Boolean)objFlag; Console.WriteLine("IPMI Supported " + infoFlag); } else { Console.WriteLine("\nIPMI Flag not set"); } objFlag = getObjectProperty(hmor, "capability.tpmSupported"); if (objFlag != null) { Boolean infoFlag = (Boolean)objFlag; Console.WriteLine("TPM Supported " + infoFlag); } else { Console.WriteLine("\nTPM Flag not set"); } } } else { Object[] vmProps = getProperties(hmor, new String[] { "name" }); String serverName = (String)vmProps[0]; Console.WriteLine("Server Name " + serverName); } } else { Console.WriteLine("Host Not Found"); } }
public void Connect(string url, Cookie cookie) { if (_service != null) { Disconnect(); } _service = new VimService(); _service.Url = url; _service.Timeout = 600000; //The value can be set to some higher value also. _service.CookieContainer = new System.Net.CookieContainer(); _service.CookieContainer.Add(cookie); _sic = _service.RetrieveServiceContent(_svcRef); _state = ConnectionState.Connected; if (AfterConnect != null) { AfterConnect(this, new ConnectionEventArgs()); } }
private void getVMFiles(String[] args) { _service = cb.getConnection()._service; _sic = cb.getConnection()._sic; String vmName = cb.get_option("vmname"); String localpath = cb.get_option("localpath"); Hashtable downloadedDir = new Hashtable(); try { Cookie cookie = cb._connection._service.CookieContainer.GetCookies( new Uri(cb.get_option("url")))[0]; CookieContainer cookieContainer = new CookieContainer(); cookieContainer.Add(cookie); ManagedObjectReference vmmor = null; vmmor = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); if (vmmor != null) { String dataCenterName = getDataCenter(vmmor); String[] vmDirectory = getVmDirectory(vmmor); if (vmDirectory[0] != null) { Console.WriteLine("Downloading Virtual Machine Configuration Directory"); String dataStoreName = vmDirectory[0].Substring(vmDirectory[0].IndexOf("[") + 1, vmDirectory[0].LastIndexOf("]") - 1); int length = vmDirectory[0].LastIndexOf("/") - vmDirectory[0].IndexOf("]") - 2; String configurationDir = vmDirectory[0].Substring(vmDirectory[0].IndexOf("]") + 2, length); String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vm#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vm#" + dataStoreName, "Directory"); Console.WriteLine("Downloading Virtual Machine" + " Configuration Directory Complete"); } if(vmDirectory[1] != null) { Console.WriteLine("Downloading Virtual Machine Snapshot / Suspend / Log Directory"); for(int i=1; i < vmDirectory.Length; i++) { String dataStoreName = vmDirectory[i].Substring(vmDirectory[i].IndexOf("[") +1,vmDirectory[i].LastIndexOf("]")-1); String configurationDir = ""; ServiceContent sc = cb.getConnection().ServiceContent; String apiType = sc.about.apiType; if(apiType.Equals("VirtualCenter")) { configurationDir = vmDirectory[i].Substring(vmDirectory[i].IndexOf("]")+2); configurationDir = configurationDir.Substring(0,configurationDir.Length-1); } else { configurationDir = vmDirectory[i].Substring(vmDirectory[i].IndexOf("]")+2); } if(!downloadedDir.ContainsKey(configurationDir+"#vm#"+dataStoreName)) { String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vm#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vm#" + dataStoreName, "Directory"); } else { Console.WriteLine("Already Downloaded"); } } Console.WriteLine("Downloading Virtual Machine Snapshot" +" / Suspend / Log Directory Complete"); } String [] virtualDiskLocations = getVDiskLocations(vmmor); if(virtualDiskLocations != null) { Console.WriteLine("Downloading Virtual Disks"); for(int i=0; i<virtualDiskLocations.Length; i++) { if(virtualDiskLocations[i]!=null) { String dataStoreName = virtualDiskLocations[i].Substring( virtualDiskLocations[i].IndexOf("[") +1,virtualDiskLocations[i].LastIndexOf("]")-1); String configurationDir = virtualDiskLocations[i].Substring( virtualDiskLocations[i].IndexOf("]") + 2, virtualDiskLocations[i].LastIndexOf("/") - virtualDiskLocations[i].IndexOf("]") - 2); if(!downloadedDir.ContainsKey(configurationDir+"#vdisk#"+dataStoreName)) { String localDirPath = cb.get_option("localpath") + "/" + configurationDir + "#vdisk#" + dataStoreName; Directory.CreateDirectory(localDirPath); downloadDirectory(configurationDir, localDirPath, dataStoreName, dataCenterName); downloadedDir.Add(configurationDir + "#vdisk#" + dataStoreName, "Directory"); } else { Console.WriteLine("Already Downloaded"); } } else { // Do Nothing } } Console.WriteLine("Downloading Virtual Disks Complete"); } else { // Do Nothing } } else { Console.WriteLine("Virtual Machine " + cb.get_option("vmname") + " Not Found."); } } catch (Exception e) { cb.log.LogLine("GetVMFiles failed for VM : " + vmName); throw e; } }