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); }
/// <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 } }
/// <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 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"); } }
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> /// 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 (vimService != null) { if (vConnection != null) { vimService.Logout(new VimApi_55.ManagedObjectReference() { type = vConnection.SessionManager.Type, Value = vConnection.SessionManager.Value }); } vimService.Dispose(); vimService = null; vConnection = null; } vimService = new VimService(); vimService.Url = url; vimService.Timeout = 600000; //The value can be set to some higher value also. vimService.CookieContainer = new System.Net.CookieContainer(); if (vConnection.SessionManager != null) { vimService.Login(new VimApi_55.ManagedObjectReference() { type = vConnection.SessionManager.Type, Value = vConnection.SessionManager.Value }, username, password, null); } }
/// <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()); } } }
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; }
private void getQueryAvailable(ManagedObjectReference perfMgr, ManagedObjectReference hostmor, VimService service) { DateTime end = DateTime.Now; DateTime start = end.AddHours(-12); PerfMetricId[] metricIds = service.QueryAvailablePerfMetric(perfMgr, hostmor, start, true, end, true, 20, true); int[] ids = new int[metricIds.Length]; for (int i = 0; i != metricIds.Length; ++i) { ids[i] = metricIds[i].counterId; } PerfCounterInfo[] counters = service.QueryPerfCounter(perfMgr, ids); Console.WriteLine("Available metrics for host (" + metricIds.Length + "):"); Console.WriteLine("--------------------------"); for (int i = 0; i != metricIds.Length; ++i) { String label = counters[i].nameInfo.label; String instance = metricIds[i].instance; Console.WriteLine(" " + label); if (instance.Length != 0) { Console.WriteLine(" [" + instance + "]"); } Console.WriteLine(); } Console.WriteLine(); }
/** * 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; }
private void FileTransferToGuest(VimService service, string vmKey, string username, string password, string fileName, byte[] fileData) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var fileMgr = new ManagedObjectReference { type = "GuestFileManager", Value = "guestOperationsFileManager" }; var posixFileAttributes = new GuestPosixFileAttributes(); posixFileAttributes.ownerId = 1; posixFileAttributes.groupId = 1; posixFileAttributes.permissions = (long)0777; //execution file var requestUrl = service.InitiateFileTransferToGuest(fileMgr, vmRef, auth, fileName, posixFileAttributes, fileData.Length, true); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); request.ContentType = "application/octet-stream"; request.Method = "PUT"; request.ContentLength = fileData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileData, 0, fileData.Length); requestStream.Close(); request.GetResponse(); }
//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; //} }
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(); } }
public void Disconnect() { if (vimService != null) { vimService.Dispose(); vimService = 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 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 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) { } }
/// <summary> /// Creates new LoginByTokenSample object /// </summary> /// <param name="serverUrl">Server url to login to</param> public LoginByTokenSample(string serverUrl) { _service = new VimService(); _service.Url = serverUrl; _serverUrl = serverUrl; _service.CookieContainer = new System.Net.CookieContainer(); _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; }
public void Disconnect() { if (_service != null) { _service.Logout(_sic.sessionManager); _service.Dispose(); _service = null; _sic = null; } }
/// <summary> /// Resetting the VimService without the security policies /// as we need the policy only for the LoginByToken method /// and not the other API. The method also maintains the /// authenticated session cookie post LoginByLogin. /// /// This method needs to be called only after successful /// login /// </summary> private void resetService() { var _cookie = getCookie(); _service = new VimService(); _service.Url = _serverUrl; _service.CookieContainer = new CookieContainer(); if (_cookie != null) { _service.CookieContainer.Add(_cookie); } }
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 ManagedObjectReference GetVMs(string _name, ManagedObjectReference[] vmList, bool first) { ManagedObjectReference vmRef = null; for (int ii = 0; ii < vmList.Length; ii++) { if (boolVMFound == true) { break; } if (vmList[ii].type == "VirtualMachine") { //Object[] vmProps = oVMware.getProperties(vmList[ii], new String[] { "name", "config.name", "config.template" }); //if (((String)vmProps[0]).ToUpper() == _name.ToUpper()) //if (oVMware.getObjectProperty(vmList[ii], "name").ToString().ToUpper() == _name.ToUpper()) PropertySpec pSpec = new PropertySpec(); pSpec.type = vmList[ii].type; pSpec.pathSet = new String[] { "name" }; ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = vmList[ii]; PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = new PropertySpec[] { pSpec }; pfSpec.objectSet = new ObjectSpec[] { oSpec }; VimService _service = oVMware.GetService(); ServiceContent _sic = oVMware.GetSic(); ObjectContent[] ocs = new ObjectContent[20]; ocs = _service.RetrieveProperties(_sic.propertyCollector, new PropertyFilterSpec[] { pfSpec }); string strName = ""; if (ocs.Length == 1 && ocs[0].propSet.Length == 1) { strName = ocs[0].propSet[0].val.ToString(); } if (strName.ToUpper() == _name.ToUpper()) { boolVMFound = true; vmRef = vmList[ii]; //UpdateGuestVIM(_name, vmRef.Value); break; } } //else if (vmList[ii].type == "Folder") //{ // if (chkGroups.Checked || (String.IsNullOrEmpty(txtGroup.Text) == false && oVMware.getObjectProperty(vmList[ii], "name").ToString().ToUpper() == txtGroup.Text.ToUpper())) // { // vmRef = GetVMs(_name, (ManagedObjectReference[])oVMware.getObjectProperty(vmList[ii], "childEntity"), false); // if (boolVMFound == true) // break; // } //} } return(vmRef); }
private Object getProperty(VimService service, ManagedObjectReference moRef, String prop) { Object[] props = getProperties(service, moRef, new String[] { prop }); if (props.Length > 0) { return(props[0]); } else { return(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 CBTQuery(AppUtil.AppUtil cb) { this.cb = cb; if (cb != null) { this.su = cb.getServiceUtil(); this.vimservice = cb.getConnection()._service; } else { this.su = null; this.vimservice = null; } }
private void getIntervals(ManagedObjectReference perfMgr, VimService service) { Object property = getProperty(service, perfMgr, "historicalInterval"); PerfInterval[] intervals = (PerfInterval[])property; // PerfInterval [] intervals = arrayInterval.perfInterval; Console.WriteLine("Performance intervals (" + intervals.Length + "):"); Console.WriteLine("---------------------"); for (int i = 0; i != intervals.Length; ++i) { PerfInterval interval = intervals[i]; Console.WriteLine(i + ": " + interval.name); Console.WriteLine(" -- period = " + interval.samplingPeriod); Console.WriteLine(", length = " + interval.length); } Console.WriteLine(); }
private void getQuerySummary(ManagedObjectReference perfMgr, ManagedObjectReference hostmor, VimService service) { PerfProviderSummary summary = service.QueryPerfProviderSummary(perfMgr, hostmor); Console.WriteLine("Host perf capabilities:"); Console.WriteLine("----------------------"); Console.WriteLine(" Summary supported: " + summary.summarySupported); Console.WriteLine(" Current supported: " + summary.currentSupported); if (summary.currentSupported) { Console.WriteLine(" Current refresh rate: " + summary.refreshRate); } Console.WriteLine(); }
private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments }; var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" }; var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec); }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); string strConnect = oVMWare.ConnectDEBUG("https://ohcleutl4001/sdk", 3, "Dalton"); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); string strName = "txpv00001a"; ManagedObjectReference _vm_boot_order = oVMWare.GetVM(strName); OptionValue oValue = new OptionValue(); oValue.key = "bios.bootDeviceClasses"; // Set the PXE boot oValue.value = "allow:net"; // Remove the PXE boot oValue.value = ""; VirtualMachineConfigSpec _cs_boot_order = new VirtualMachineConfigSpec(); _cs_boot_order.extraConfig = new OptionValue[] { oValue }; ManagedObjectReference _task_boot_order = _service.ReconfigVM_Task(_vm_boot_order, _cs_boot_order); TaskInfo _inf_boot_order = (TaskInfo)oVMWare.getObjectProperty(_task_boot_order, "info"); while (_inf_boot_order.state == TaskInfoState.running) { _inf_boot_order = (TaskInfo)oVMWare.getObjectProperty(_task_boot_order, "info"); } if (_inf_boot_order.state == TaskInfoState.success) { strResult = "PXE Boot Forced"; } else { strResult = "PXE Boot NOT Forced"; } Response.Write(strResult); } else { Response.Write("LOGIN error"); } }
private void getCounters(ManagedObjectReference perfMgr, VimService service) { Object property = getProperty(service, perfMgr, "perfCounter"); PerfCounterInfo[] counters = (PerfCounterInfo[])property; // PerfCounterInfo[] counters = arrayCounter.getPerfCounterInfo(); Console.WriteLine("Performance counters (averages only):"); Console.WriteLine("-------------------------------------"); foreach (PerfCounterInfo counter in counters) { if (counter.rollupType == PerfSummaryType.average) { ElementDescription desc = counter.nameInfo; Console.WriteLine(desc.label + ": " + desc.summary); } } Console.WriteLine(); }
private ServiceContent RetrieveServiceContent(VimService service) { var serviceInstance = new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }; var content = service.RetrieveServiceContent(serviceInstance); if (content.sessionManager == null) { throw new ApplicationException("Session manager is null."); } return(content); }
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()); } }
public Object getProperties(ManagedObjectReference moRef, String propertyName) { PropertySpec pSpec = new PropertySpec(); pSpec.type = moRef.type; pSpec.pathSet = new String[] { propertyName }; ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = moRef; PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = new PropertySpec[] { pSpec }; pfSpec.objectSet = new ObjectSpec[] { oSpec }; ObjectContent[] ocs = new ObjectContent[20]; VimService _service = oVMware.GetService(); ServiceContent _sic = oVMware.GetSic(); ocs = _service.RetrieveProperties(_sic.propertyCollector, new PropertyFilterSpec[] { pfSpec }); Object ret = new Object(); for (int ii = 0; ocs != null && ii < ocs.Length; ++ii) { ObjectContent oc = ocs[ii]; DynamicProperty[] dps = oc.propSet; for (int jj = 0; dps != null && jj < dps.Length; ++jj) { DynamicProperty dp = dps[jj]; if (propertyName.Equals(dp.name)) { ret = dp.val; break; } } if (ret != null) { break; } } return(ret); }
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"); } }
private Object getProperty(VimService service, ManagedObjectReference moRef, String prop) { Object[] props = getProperties(service, moRef, new String[] { prop }); if (props.Length > 0) { return props[0]; } else { return null; } }
/// <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()); } } }
private Object[] getProperties(VimService service, ManagedObjectReference moRef, String[] properties) { PropertySpec pSpec = new PropertySpec(); pSpec.type = moRef.type; pSpec.pathSet = properties; ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = moRef; PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = (new PropertySpec[] { pSpec }); pfSpec.objectSet = (new ObjectSpec[] { oSpec }); ObjectContent[] ocs = service.RetrieveProperties(sic.propertyCollector, new PropertyFilterSpec[] { pfSpec }); Object[] ret = new Object[properties.Length]; if (ocs != null) { for (int i = 0; i < ocs.Length; ++i) { ObjectContent oc = ocs[i]; DynamicProperty[] dps = oc.propSet; if (dps != null) { for (int j = 0; j < dps.Length; ++j) { DynamicProperty dp = dps[j]; for (int p = 0; p < ret.Length; ++p) { if (properties[p].Equals(dp.name)) { ret[p] = dp.val; } } } } } } return ret; }
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()); } }
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 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 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(); }
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()); } }
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(); }
/** 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) { } }
private void createVM() { _service = cb.getConnection()._service; String dcName = cb.get_option("datacentername"); ManagedObjectReference dcmor = cb.getServiceUtil().GetDecendentMoRef(null,"Datacenter",dcName); if(dcmor == null) { Console.WriteLine("Datacenter " + dcName + " not found."); return; } try { ManagedObjectReference hfmor = cb.getServiceUtil().GetMoRefProp(dcmor, "hostFolder"); ArrayList crmors = cb.getServiceUtil().GetDecendentMoRefs(hfmor, "ComputeResource", null); String hostName = cb.get_option("hostname"); ManagedObjectReference hostmor; if (hostName != null) { hostmor = cb.getServiceUtil().GetDecendentMoRef(hfmor, "HostSystem", hostName); if(hostmor == null) { Console.WriteLine("Host " + hostName + " not found"); return; } } else { hostmor = cb.getServiceUtil().GetFirstDecendentMoRef(dcmor, "HostSystem"); } ManagedObjectReference crmor = null; 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(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; } ManagedObjectReference resourcePool = cb.getServiceUtil().GetMoRefProp(crmor, "resourcePool"); ManagedObjectReference vmFolderMor = cb.getServiceUtil().GetMoRefProp(dcmor, "vmFolder"); VirtualMachineConfigSpec vmConfigSpec = vmUtils.createVmConfigSpec(cb.get_option("vmname"), cb.get_option("datastorename"), int.Parse(cb.get_option("disksize")), crmor, hostmor); vmConfigSpec.name=cb.get_option("vmname"); vmConfigSpec.annotation="VirtualMachine Annotation"; vmConfigSpec.memoryMB= (long)(int.Parse(cb.get_option("memorysize"))); vmConfigSpec.memoryMBSpecified = true; vmConfigSpec.numCPUs = int.Parse(cb.get_option("cpucount")); vmConfigSpec.numCPUsSpecified = true; vmConfigSpec.guestId= (cb.get_option("guestosid")); ManagedObjectReference taskmor = _service.CreateVM_Task( vmFolderMor, vmConfigSpec, resourcePool, hostmor ); String res = cb.getServiceUtil().WaitForTask(taskmor); if(res.Equals("sucess")) { Console.WriteLine("Virtual Machine Created Sucessfully"); } else { Console.WriteLine("Virtual Machine could not be created. "); } } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } }
/// <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(); }
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; } }