/** * 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; }
/// <summary> /// Destroy the Profile /// </summary> /// <param name="hostProfile">ManagedObjectReference</param> private void DeleteHostProfile(ManagedObjectReference hostProfile) { Console.WriteLine("Deleting Profile"); Console.WriteLine("---------------"); cb._connection._service.DestroyProfile(hostProfile); Console.WriteLine("Profile Deleted : " + hostProfile.Value); }
private PropertyFilterSpec[] createPFSForRecentTasks( ManagedObjectReference taskManagerRef) { PropertySpec pSpec = new PropertySpec(); pSpec.all= false; pSpec.type="Task"; pSpec.pathSet= new String[] {"info.entity", "info.entityName", "info.name", "info.state", "info.cancelled", "info.error"}; ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = taskManagerRef; oSpec.skip= false; oSpec.skipSpecified = true; TraversalSpec tSpec = new TraversalSpec(); tSpec.type="TaskManager"; tSpec.path="recentTask"; tSpec.skip= false; oSpec.selectSet=new SelectionSpec[]{tSpec}; PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet=new PropertySpec[]{pSpec}; pfSpec.objectSet=new ObjectSpec[]{oSpec}; return new PropertyFilterSpec[]{pfSpec}; }
/** * 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 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]"); } }
/* * This subroutine prints the virtual machine file * system volumes affected by the given SCSI LUN. * @param hmor A HostSystem object of the given host. * @param canName Canonical name of the SCSI logical unit */ private void getVMFS(ManagedObjectReference hmor,String canName) { DynamicProperty[] dsArr = getDynamicProarray(hmor,"datastore"); ManagedObjectReference[] dataStoresMOR = ((ManagedObjectReference[])(dsArr[0]).val); //ManagedObjectReference[] dataStoresMOR = ds.managedObjectReference; Boolean vmfsFlag = false; try { for (int j=0;j<dataStoresMOR.Length ; j++ ) { DynamicProperty[] infoArr = getDynamicProarray(dataStoresMOR[j],"info"); String infoClass = infoArr[0].val.GetType().ToString(); if(infoClass.Equals("VmfsDatastoreInfo")){ VmfsDatastoreInfo vds = (VmfsDatastoreInfo)(infoArr[0]).val; HostVmfsVolume hvms = vds.vmfs; String vmfsName = vds.name; HostScsiDiskPartition[] hdp = hvms.extent; for (int k =0;k< hdp.Length ; k++ ) { if(hdp[k].diskName.Equals(canName)){ vmfsFlag = true; Console.WriteLine(" " + vmfsName + "\n"); } } } } if (!vmfsFlag) { Console.WriteLine(" None\n"); } } catch(Exception e) { Console.WriteLine("error" + e); e.StackTrace.ToString(); } }
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 Boolean findVirtualMachine() { String vmPath = cb.get_option("vmpath"); // Console.Write(vmPath); _virtualMachine = _service.FindByInventoryPath(_searchIndex, vmPath); if(_virtualMachine !=null){ return true; } else return false; }
/* * getProperties -- * * Retrieves the specified set of properties for the given managed object * reference into an array of result objects (returned in the same oder * as the property list). */ public static Object[] getProperties(ManagedObjectReference moRef, String[] properties) { // PropertySpec specifies what properties to // retrieve and from type of Managed Object PropertySpec pSpec = new PropertySpec(); pSpec.type = moRef.type; pSpec.pathSet = properties; // ObjectSpec specifies the starting object and // any TraversalSpecs used to specify other objects // for consideration ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = moRef; // PropertyFilterSpec is used to hold the ObjectSpec and // PropertySpec for the call PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = new PropertySpec[] { pSpec }; pfSpec.objectSet = new ObjectSpec[] { oSpec }; // retrieveProperties() returns the properties // selected from the PropertyFilterSpec ObjectContent[] ocs = new ObjectContent[20]; ocs = ecb._svcUtil.retrievePropertiesEx(_sic.propertyCollector, new PropertyFilterSpec[] { pfSpec }); // Return value, one object for each property specified 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]; // find property path index for (int p = 0; p < ret.Length; ++p) { if (properties[p].Equals(dp.name)) { ret[p] = dp.val; } } } } } } return ret; }
public SvcConnection(string svcRefVal) { _state = ConnectionState.Disconnected; if (ignoreCert) { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate); } _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = svcRefVal; }
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); } }
private void ProfileManager() { string hostName = cb.get_option("sourcehostname"); string entityType = cb.get_option("entitytype"); string entityName = cb.get_option("entityname"); try { hostprofileManager = cb._connection._sic.hostProfileManager; profilecomplianceManager = cb._connection._sic.complianceManager; ManagedObjectReference hostmor = cb._svcUtil.getEntityByName("HostSystem", hostName); ManagedObjectReference hostProfile = CreateHostProfile(hostmor, hostName); ManagedObjectReference attachMoref = cb._svcUtil.getEntityByName(entityType, entityName); List<ManagedObjectReference> entityMorList = new List<ManagedObjectReference>(); entityMorList.Add(attachMoref); ManagedObjectReference[] entityList = entityMorList.ToArray(); AttachProfileWithManagedEntity(hostProfile, entityList); PrintProfilesAssociatedWithEntity(attachMoref); List<ManagedObjectReference> hpmor = new List<ManagedObjectReference>(); List<ManagedObjectReference> hamor = new List<ManagedObjectReference>(); hpmor.Add(hostProfile); hamor.Add(attachMoref); if (entityType.Equals("HostSystem")) { UpdateReferenceHost(hostProfile, attachMoref); HostConfigSpec hostConfigSpec = ExecuteHostProfile(hostProfile, attachMoref); if (hostConfigSpec != null) { ConfigurationTasksToBeAppliedOnHost(hostConfigSpec, attachMoref); if (CheckProfileCompliance(hpmor.ToArray(), hamor.ToArray())) { ApplyConfigurationToHost(attachMoref, hostConfigSpec); } } } else { CheckProfileCompliance(hpmor.ToArray(), hamor.ToArray()); } DetachHostFromProfile(hostProfile, hamor.ToArray()); DeleteHostProfile(hostProfile); } catch (Exception e) { throw new Exception(e.Message); } }
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 createEventHistoryCollector() { // Create an Entity Event Filter Spec to // specify the MoRef of the VM to be get events filtered for EventFilterSpecByEntity entitySpec = new EventFilterSpecByEntity(); entitySpec.entity =_virtualMachine; // we are only interested in getting events for the VM entitySpec.recursion = EventFilterSpecRecursionOption.self; // set the entity spec in the EventFilter EventFilterSpec eventFilter = new EventFilterSpec(); eventFilter.entity = entitySpec; // create the EventHistoryCollector to monitor events for a VM // and get the ManagedObjectReference of the EventHistoryCollector returned _eventHistoryCollector = _service.CreateCollectorForEvents(_eventManager, eventFilter); }
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 Boolean createSnapshot(ManagedObjectReference vmMor) { String snapshotName = cb.get_option("snapshotname"); String desc = cb.get_option("description"); ManagedObjectReference taskMor = cb.getConnection()._service.CreateSnapshot_Task( vmMor, snapshotName, desc, false, false); String res = cb.getServiceUtil().WaitForTask(taskMor); if (res.Equals("sucess")) { revertSnapshot(vmMor); removeSnapshot(vmMor); listSnapshot(vmMor); return true; } return false; }
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 Boolean revertSnapshot(ManagedObjectReference vmMor) { String snapshotName = cb.get_option("snapshotname"); bool suppressPowerOn = false; ManagedObjectReference snapmor = getSnapshotReference(vmMor, cb.get_option("vmname"), cb.get_option("snapshotname")); if (snapmor != null) { ManagedObjectReference taskMor = cb.getConnection()._service.RevertToSnapshot_Task(snapmor, null, suppressPowerOn, false); String res = cb.getServiceUtil().WaitForTask(taskMor); if (res.Equals("sucess")) { return true; } } else { Console.WriteLine("Snapshot not found"); } return false; }
private void createAlarm(AlarmSpec alarmSpec) { try { _alarmManager = cb.getConnection()._sic.alarmManager; ManagedObjectReference alarm = cb.getConnection()._service.CreateAlarm(_alarmManager, _virtualMachine, alarmSpec); Console.WriteLine("Successfully created Alarm: " + cb.get_option("alarm")); } catch(SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("DuplicateNameFault")) { Console.WriteLine(e.Message.ToString()); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidRequestFault")) { Console.WriteLine("Alarm Creation is not supported on ESX server."); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault")) { Console.WriteLine(e.Message.ToString()); } else if (e.Detail.FirstChild.LocalName.Equals("InvalidNameFault")) { Console.WriteLine(e.Message.ToString()); } else if (e.Detail.FirstChild.LocalName.Equals("RuntimeFault")) { Console.WriteLine(e.Message.ToString()); } else { throw e; } } }
private Boolean listSnapshot(ManagedObjectReference vmMor) { ObjectContent[] snaps = cb.getServiceUtil().GetObjectProperties( null, vmMor, new String[] { "snapshot" }); VirtualMachineSnapshotInfo snapInfo = null; if (snaps != null && snaps.Length > 0) { ObjectContent snapobj = snaps[0]; DynamicProperty[] snapary = snapobj.propSet; if (snapary != null && snapary.Length > 0) { snapInfo = ((VirtualMachineSnapshotInfo)(snapary[0]).val); VirtualMachineSnapshotTree[] snapTree = snapInfo.rootSnapshotList; traverseSnapshotInTree(snapTree, null, true); } else { Console.WriteLine("No Snapshots found"); return false; } } return true; }
public static ObjectContent FindTypeByReference(this ObjectContent[] tree, ManagedObjectReference mor) { return(tree .Where(o => o.obj.type == mor.type && o.obj.Value == mor.Value) .SingleOrDefault()); }
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; }
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; } }
public static int MainFindVM(MainSearchVM_In inParam, MainSearchVM_Out outRet) { VmSummaryInfo vmSummaryInfo = new VmSummaryInfo(); System.Net.ServicePointManager.Expect100Continue = false; MyCertVerify certVerify = new MyCertVerify(); System.Net.ServicePointManager.ServerCertificateValidationCallback = certVerify.RemoteCertificateValidationCallback; BasicHttpBinding binding = null; if (string.Compare("https", inParam.Protocal, StringComparison.InvariantCultureIgnoreCase) == 0) { binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport) { AllowCookies = true, OpenTimeout = TimeSpan.FromHours(1), ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), CloseTimeout = TimeSpan.FromHours(1), MaxBufferPoolSize = 1024 * 1024 * 2, MaxReceivedMessageSize = 1024 * 512, MaxBufferSize = 1024 * 512 }; } else { binding = new BasicHttpBinding() { AllowCookies = true, OpenTimeout = TimeSpan.FromHours(1), ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), CloseTimeout = TimeSpan.FromHours(1), MaxBufferPoolSize = 1024 * 1024 * 2, MaxReceivedMessageSize = 1024 * 512, MaxBufferSize = 1024 * 512 }; } string sdkUrl = string.Format("{0}://{1}{2}/sdk", inParam.Protocal, inParam.ServerName, 0 == inParam.Port ? "" : ":" + inParam.Port.ToString()); EndpointAddress epa = new EndpointAddress(sdkUrl); vmSummaryInfo.VmHost.ServerName = inParam.ServerName; vmSummaryInfo.VmHost.UserName = inParam.User; vmSummaryInfo.VmHost.Password = inParam.Password; vmSummaryInfo.VmHost.Port = inParam.Port; StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (var vimClient = new VimPortTypeClient(binding, epa)) { //var serviceCertificate = vimClient.ClientCredentials.ServiceCertificate; //serviceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; //serviceCertificate.Authentication.CustomCertificateValidator = new MyX509CertificateValidator(null); //serviceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; //var clientCertificate = vimClient.ClientCredentials.ClientCertificate; try { ManagedObjectReference morServiceInstance = new ManagedObjectReference() { @type = "ServiceInstance", Value = "ServiceInstance" }; ServiceContent sc = vimClient.RetrieveServiceContent(morServiceInstance); vmSummaryInfo.VmHost.ThumbPrint = StaticHelpers.FormatThumbPrint(certVerify.Thumbprint); sb.AppendFormat("{0}, {1}, {2}, {3}, {4}", epa.Uri, inParam.User, inParam.Password, vmSummaryInfo.VmHost.ThumbPrint, certVerify.Thumbprint); sb.AppendLine(); //StaticHelpers.PrintServerAboutInfo(sb, sc.about); sc.about.Dump(nameof(sc.about), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); using (MyCollectionDisposable collectionDisposal = new MyCollectionDisposable()) { UserSession userSession = vimClient.Login(sc.sessionManager, inParam.User, inParam.Password, null); collectionDisposal.Add(() => vimClient.Logout(sc.sessionManager)); //bool bListAllVMs = false; //if(bListAllVMs) if (inParam.ToListAllVMs) { CListVMs listVMs = new CListVMs(vimClient, sc.propertyCollector); listVMs.list_all_vms(sc); } VimPropCollector pc = new VimPropCollector(vimClient, sc.propertyCollector); VimFinder vimFinder = new VimFinder(vimClient, sc.propertyCollector, sc.rootFolder); List <ManagedObjectReference> morDatacenters = new List <ManagedObjectReference>(); vimFinder.FindDatacenters(morDatacenters); foreach (var datacenter in morDatacenters) { try { ManagedObjectReference morVM = (ManagedObjectReference)vimClient.FindByDatastorePath(sc.searchIndex, datacenter, inParam.VmPath); if (null != morVM) { vmSummaryInfo.VmHost.VmxSpec = "moref=" + morVM.Value; VirtualMachineConfigInfo virtualMachineConfigInfo = (VirtualMachineConfigInfo)pc.Get(morVM, "config"); //StaticHelpers.PrintMor(sb, morVM); morVM.Dump(nameof(morVM), sw, false); //StaticHelpers.PrintVMCI(sb, virtualMachineConfigInfo); StaticHelpers.PrintVirtualDisksBriefInfo(sb, virtualMachineConfigInfo, vmSummaryInfo.VmHost.CurrentDiskPath); virtualMachineConfigInfo.Dump(nameof(virtualMachineConfigInfo), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); VimSnapshotInfo si = new VimSnapshotInfo(vimClient, sc.propertyCollector, morVM, sb, vmSummaryInfo.Snapshots); si.Traverse(); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); //datastore ManagedObjectReference:Datastore[] datastore-983 (datastore_on_30_1T) var datastore = (ManagedObjectReference[])pc.Get(morVM, "datastore"); if (null != datastore) { var datastoreName = from item in datastore select new { Datastore = item, DatastoreName = (string)pc.Get(item, "name") }; foreach (var item in datastoreName) { sb.AppendLine(); //StaticHelpers.PrintMor(sb, item.Datastore); item.Datastore.Dump(nameof(item.Datastore), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(item.DatastoreName), item.DatastoreName); sb.AppendLine(); } } //guest GuestInfo guest var guest = (GuestInfo)pc.Get(morVM, "guest"); //StaticHelpers.PrintGuestInfo(sb, guest); guest.Dump(nameof(guest), sw, false); //layout VirtualMachineFileLayout layout var layout = (VirtualMachineFileLayout)pc.Get(morVM, "layout"); //StaticHelpers.PrintVirtualMachineFileLayout(sb, layout); layout.Dump(nameof(layout), sw, false); //layoutEx VirtualMachineFileLayoutEx layoutEx var layoutEx = (VirtualMachineFileLayoutEx)pc.Get(morVM, "layoutEx"); //StaticHelpers.PrintVirtualMachineFileLayoutEx(sb, layoutEx); layoutEx.Dump(nameof(layoutEx), sw, false); //name string "shuli02-vc60" var name = (string)pc.Get(morVM, "name"); sb.AppendFormat("{0}\t\"{1}\"", nameof(name), name); //network ManagedObjectReference:Network[] network-822(VM Network) var network = (ManagedObjectReference[])pc.Get(morVM, "network"); if (null != network) { foreach (var Network in network) { //StaticHelpers.PrintMor(sb, Network); Network.Dump(nameof(Network), sw, false); } } //parent ManagedObjectReference:Folder group-v3 (vm) var parent = (ManagedObjectReference)pc.Get(morVM, "parent"); //StaticHelpers.PrintMor(sb, parent); parent.Dump(nameof(parent), sw, false); //resourceConfig ResourceConfigSpec resourceConfig var resourceConfig = (ResourceConfigSpec)pc.Get(morVM, "resourceConfig"); //StaticHelpers.PrintResourceConfigSpec(sb, resourceConfig); resourceConfig.Dump(nameof(resourceConfig), sw, false); //resourcePool ManagedObjectReference:ResourcePool resgroup-980 (VC) var resourcePool = (ManagedObjectReference)pc.Get(morVM, "resourcePool"); //StaticHelpers.PrintMor(sb, resourcePool); resourcePool.Dump(nameof(resourcePool), sw, false); //runtime VirtualMachineRuntimeInfo runtime var runtime = (VirtualMachineRuntimeInfo)pc.Get(morVM, "runtime"); //StaticHelpers.PrintVirtualMachineRuntimeInfo(sb, runtime); runtime.Dump(nameof(runtime), sw, false); string runtimeHostName = (string)pc.Get(runtime.host, "name"); ManagedObjectReference morRuntimehostParent = (ManagedObjectReference)pc.Get(runtime.host, "parent"); string runtimeHostParentName = (string)pc.Get(morRuntimehostParent, "name"); //StaticHelpers.PrintMor(sb, runtime.host); runtime.host.Dump(nameof(runtime.host), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostName), runtimeHostName); sb.AppendLine(); sb.AppendLine(); //StaticHelpers.PrintMor(sb, morRuntimehostParent); morRuntimehostParent.Dump(nameof(morRuntimehostParent), sw, false); sb.AppendFormat("{0}\t\"{1}\"", nameof(runtimeHostParentName), runtimeHostParentName); sb.AppendLine(); sb.AppendLine(); //storage VirtualMachineStorageInfo storage var storage = (VirtualMachineStorageInfo)pc.Get(morVM, "storage"); //StaticHelpers.PrintVirtualMachineStorageInfo(sb, storage); storage.Dump(nameof(storage), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); //summary VirtualMachineSummary summary var summary = (VirtualMachineSummary)pc.Get(morVM, "summary"); //StaticHelpers.PrintVirtualMachineSummary(sb, summary); summary.Dump(nameof(summary), sw, false); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); ///////////////////////////////////////////////////////////////////////////////////////////// sb.Append('~', 80); sb.AppendLine(); sb.Append('~', 80); sb.AppendLine(); vmSummaryInfo.Dump(nameof(vmSummaryInfo), sw, false); sb.Append('~', 80); sb.AppendLine(); sb.Append('~', 80); sb.AppendLine(); Console.WriteLine("{0}", sb.ToString()); sb.Clear(); ///////////////////////////////////////////////////////////////////////////////////////////// bool testVmOperation = false; if (testVmOperation) { try { MyVMOperation vmop = new MyVMOperation(vimClient, sc.propertyCollector, morVM); TaskInfoState state = vmop.ConsolidateVMDisks(); string snapshotid1 = null; state = vmop.CreateSnapshot("test snapshot name 1", "test snapshot description1 ", false, true, out snapshotid1); VirtualDisk[] VirtualDisks1 = vmop.QuerySnapshotVirtualDisks(snapshotid1); string snapshotid2 = null; state = vmop.CreateSnapshot("test snapshot name 2", "test snapshot description2 ", false, true, out snapshotid2); VirtualDisk[] VirtualDisks2 = vmop.QuerySnapshotVirtualDisks(snapshotid2); try { foreach (var vdisk in VirtualDisks1) { long startOffset = 0; long diskSize = vdisk.capacityInBytes == 0 ? vdisk.capacityInKB * 1024 : vdisk.capacityInBytes; while (startOffset < diskSize) { DiskChangeInfo diskChangeInfo = vmop.QueryChangedDiskAreas(snapshotid2, vdisk, startOffset); if (null != diskChangeInfo.changedArea) { foreach (var changedArea in diskChangeInfo.changedArea) { changedArea.Dump(nameof(changedArea), sw, false); } Console.WriteLine("{0}", sb.ToString()); sb.Clear(); } startOffset = diskChangeInfo.startOffset + diskChangeInfo.length; } } } catch (Exception exQueryChangedDiskAreas) { StaticHelpers.PrintException(exQueryChangedDiskAreas, 0); } state = vmop.RemoveSnapshot(snapshotid2, false, true); state = vmop.RemoveSnapshot(snapshotid1, false, true); } catch (Exception exTestVmOperation) { StaticHelpers.PrintException(exTestVmOperation, 0); } } ///////////////////////////////////////////////////////////////////////////////////////////// bool testGustOp = false; if (testGustOp) { try { string guestUser = "******"; string guestPassword = "******"; VimGuestOperation vimGuestOp = new VimGuestOperation(vimClient, sc.propertyCollector, sc.guestOperationsManager, morVM, guestUser, guestPassword); string[] vars = vimGuestOp.ReadEnvironmentVariableInGuest(new string[] { "path" }); GuestProgramSpec guestProgramSpec = new GuestProgramSpec() { programPath = @"c:\Windows\notepad.exe", arguments = "", workingDirectory = @"c:\", envVariables = null }; long pid = vimGuestOp.StartProgramInGuest(guestProgramSpec); GuestProcessInfo[] gpi = vimGuestOp.ListProcessesInGuest(new long[] { pid }); vimGuestOp.TerminateProcessInGuest(pid); string guestFilePath = @"E:\1.vhdx"; string localFile = @"E:\~temp\1.vhdx"; vimGuestOp.FileTransferFromGuest(guestFilePath, localFile); string guestFilePath2 = @"e:\111\1.vhdx"; vimGuestOp.FileTransferToGuest(guestFilePath2, localFile, true); } catch (Exception exGust) { StaticHelpers.PrintException(exGust, 0); } } } } catch (Exception exFind) { StaticHelpers.PrintException(exFind, 0); } } } } catch (Exception ex) { StaticHelpers.PrintException(ex, 0); } } return(0); }
public HostDirectoryStore(VimClient client, ManagedObjectReference moRef) : base(client, moRef) { }
static void ExecuteCommand(GuestAuthentication creds, string arguments, string programPath, string workingDirectory, bool output, bool linux) { try { ManagedObjectReference processManager = GetProperty <ManagedObjectReference>(serviceContent.guestOperationsManager, "processManager"); var guestProgramSpec = new GuestProgramSpec() { arguments = arguments, programPath = programPath, workingDirectory = workingDirectory, }; if (output) { //Set file to receive output var outfile = Path.GetRandomFileName(); string pathSymbol; if (linux) { pathSymbol = "/"; } else { pathSymbol = "\\"; } guestProgramSpec.arguments += @" > " + workingDirectory + pathSymbol + outfile + @" 2>&1"; //Start the program and receive the PID back Log("[x] Attempting to run " + programPath + " with the following arguments: " + guestProgramSpec.arguments); Log(@"[x] Temporarily saving out to " + workingDirectory + pathSymbol + outfile); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID " + pid + " waiting for execution to finish"); bool finished = false; while (!finished) { //Get status of our process long[] pids = { pid }; GuestProcessInfo[] guestProcessInfo = vim.ListProcessesInGuest(processManager, vm, creds, pids); if (guestProcessInfo.Length == 0) { Log("Error retrieving status of the process, check for the existance of the output file manually"); } if (guestProcessInfo[0].exitCodeSpecified) { Log("[x] Execution finished, attempting to retrieve the results"); //Get the results var fileTransferInformation = vim.InitiateFileTransferFromGuest(guestFileManager, vm, creds, workingDirectory + pathSymbol + outfile); using (var client = new System.Net.WebClient()) { client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); var results = client.DownloadString(fileTransferInformation.url); Log("[x] Output: "); Log(results); } //Delete the file vim.DeleteFileInGuest(guestFileManager, vm, creds, workingDirectory + pathSymbol + outfile); Log("[x] Output file deleted"); finished = true; } } } else { //Start the program and receive the PID back Log("[x] Attempting to execute the following command: " + guestProgramSpec.arguments); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID" + pid); } } catch (Exception fault) { Error(fault); } }
public object Collect(string url, string username, string password, string EntityType) { if (_service != null) { Disconnect(); } ArrayList ObjectList = new ArrayList(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Inventory.xml"); _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); } TraversalSpec rpToRp = new TraversalSpec(); rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.name = "rpToRp"; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; TraversalSpec rpToVm = new TraversalSpec(); rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.name = "rpToVm"; rpToVm.selectSet = new SelectionSpec[] { }; TraversalSpec crToRp = new TraversalSpec(); crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.name = "crToRp"; crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() }; crToRp.selectSet[1].name = "rpToVm"; TraversalSpec crToH = new TraversalSpec(); crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.name = "crToH"; crToH.selectSet = new SelectionSpec[] { }; TraversalSpec dcToHf = new TraversalSpec(); dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.name = "dcToHf"; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.name = "dcToVmf"; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; TraversalSpec HToVm = new TraversalSpec(); HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.name = "HToVm"; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders"; TraversalSpec visitFolders = new TraversalSpec(); visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.name = "visitFolders"; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, crToH, crToRp, rpToVm }; visitFolders.selectSet[0].name = "visitFolders"; TraversalSpec tSpec = default(TraversalSpec); tSpec = visitFolders; PropertySpec[] propSpecArray = null; propSpecArray = new PropertySpec[] { new PropertySpec() }; propSpecArray[0].type = EntityType; propSpecArray[0].all = true; propSpecArray[0].allSpecified = true; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propSpecArray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = _sic.rootFolder; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = new SelectionSpec[] { tSpec }; ObjectContent[] ocary = _service.RetrieveProperties(_propCol, new PropertyFilterSpec[] { spec }); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (Int32 oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; pcary = oc.propSet; string moref = mor.Value.ToString(); //string vmname =""; for (Int32 propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("childEntity"))) { try { for (Int32 i = 0; i >= 0;) { string dccheck = ((VimyyApi.ManagedObjectReference[])(pc.val))[i].type; string value = ((VimyyApi.ManagedObjectReference[])(pc.val))[i].Value; string shortvalue = value.Substring(0, 8); if (dccheck == "Datacenter") { } if (shortvalue == "domain-c") { XmlElement xmlclus = xmldoc.CreateElement(null, "Cluster", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Folder[@moref='" + moref + "']"); XmlAttribute newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = value; xmlclus.Attributes.Append(newAtt); xmlnode3.AppendChild(xmlclus); } if (shortvalue == "domain-s") { XmlElement xmlhost = xmldoc.CreateElement(null, "HostFolder", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Folder[@moref='" + moref + "']"); XmlAttribute newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = value; xmlhost.Attributes.Append(newAtt); xmlnode3.AppendChild(xmlhost); } /* * if ((pc.name.Equals("name"))) * { * ObjectList.Add(pc.val.ToString()); * * } */ i++; } } catch { } } } } } else { //("No Managed Entities retrieved!"); } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("Inventory.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); return(ObjectList); }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; 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 strName = "healytest2"; string strCluster = "CDALVMTEST01"; string strDatastore1 = "dt01-ibm-lun1"; string strDatastore2 = ""; string strVLAN = "VLAN52"; string strPortGroupName = "dvPortGroup255"; string strMACAddress = ""; string strResourcePool = ""; string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_ENT"; string strMDTbuildDB = "ServerShare"; double dblDriveC = 27.5; double dblDrive2 = 2.5; string strVMguestOS = "winNetEnterprise64Guest"; intEnvironment = 999; string strConnect = oVMWare.ConnectDEBUG("https://wdsvt100a/sdk", intEnvironment, "PNC"); if (Request.QueryString["old"] != null) { strName = "healytest"; strCluster = "ohcinxcv4003"; strDatastore1 = "CINDSSVCN40063"; strVLAN = "vlan250net"; intEnvironment = 3; strConnect = oVMWare.ConnectDEBUG("https://ohcinutl4003/sdk", intEnvironment, "Dalton"); } if (Request.QueryString["w"] != null) { strName = "healytest2"; strCluster = "CLEVDTLAB01"; strDatastore1 = "VDItest"; strDatastore2 = "pagefile01"; strPortGroupName = "dvPortGroup"; strResourcePool = "VDI"; strMDTos = "DesktopWABEx86"; strMDTtask = "VDIXP"; strMDTbuildDB = "DesktopDeploymentShare"; strVMguestOS = "windows7_64Guest"; strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", intEnvironment, "PNC-TestLab"); } if (Request.QueryString["t"] != null) { strName = "healyTest2012"; strCluster = "CLESVTLAB01"; dblDriveC = 45.00; strDatastore1 = "CTVXN00008"; strDatastore2 = "CTVXN00008"; dblDrive2 = 10.00; strPortGroupName = "dvPortGroup5"; // DHCP enabled strMDTos = "WABEx64"; strMDTtask = "W2K8R2_STD"; strMDTbuildDB = "ServerShare"; strVMguestOS = "windows8Server64Guest"; strConnect = oVMWare.ConnectDEBUG("https://wcsvt013a.pnceng.pvt/sdk", (int)CurrentEnvironment.PNCENG, "PNC"); } Variables oVariable = new Variables(intEnvironment); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); int intStep = 0; Int32.TryParse(Request.QueryString["s"], out intStep); string strUUID = ""; ManagedObjectReference oComputer = null; if (intStep == 100 || intStep == 1) { if (oComputer != null && oComputer.Value != "") { // Destroy computer ManagedObjectReference _task_power = _service.Destroy_Task(oComputer); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine " + strName.ToUpper() + " Destroyed<br/>"; } else { strError = "Virtual Machine was not destroyed"; } } if (strError == "") { // Create computer oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; oConfig.firmware = "efi"; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore1 + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } } } if (intStep > 1) { oComputer = oVMWare.GetVM(strName); } if ((intStep == 100 || intStep == 2) && strError == "") { // 2) SCSI Controller VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(true); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller Created<br/>"; } else { strError = "SCSI Controller Was Not Created"; } } if ((intStep == 100 || intStep == 3) && strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore1, dblDriveC.ToString(), 0, ""); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive Was Not Created"; } } if ((intStep == 100 || intStep == 33) && strError == "") { if (strDatastore2 != "") { // 33) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore2, dblDrive2.ToString(), 1, (strDatastore1 == strDatastore2 ? "_1" : "")); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDrive2.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } } if ((intStep == 100 || intStep == 4) && strError == "") { // 4) Create Network Adapter bool boolISVmware4 = true; if (boolISVmware4 == false) { VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardNetworkBackingInfo vecnbi = new VirtualEthernetCardNetworkBackingInfo(); vecnbi.deviceName = strVLAN; VirtualEthernetCard newethdev; //newethdev = new VirtualE1000(); newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecnbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; } else { strError = "Network Adapter Was Not Created"; } } else { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } } if ((intStep == 100 || intStep == 5) && strError == "") { VirtualMachineConfigSpec _cs_swap = new VirtualMachineConfigSpec(); _cs_swap.swapPlacement = "hostLocal"; ManagedObjectReference _task_swap = _service.ReconfigVM_Task(oComputer, _cs_swap); TaskInfo _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); while (_info_swap.state == TaskInfoState.running) { _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); } if (_info_swap.state == TaskInfoState.success) { strResult += "Swap File Configured<br/>"; } else { strError = "Swap File Was Not Configured"; } /* * // 5) Attach Floppy Drive * VirtualMachineConfigSpec _cs_floppy = new VirtualMachineConfigSpec(); * VirtualDeviceConfigSpec _dcs_floppy = new VirtualDeviceConfigSpec(); * _dcs_floppy.operation = VirtualDeviceConfigSpecOperation.add; * _dcs_floppy.operationSpecified = true; * VirtualDeviceConnectInfo _ci_floppy = new VirtualDeviceConnectInfo(); * _ci_floppy.startConnected = false; * VirtualFloppy floppy = new VirtualFloppy(); * VirtualFloppyRemoteDeviceBackingInfo floppyBack = new VirtualFloppyRemoteDeviceBackingInfo(); * floppyBack.deviceName = ""; * floppy.backing = floppyBack; * floppy.key = 8000; * floppy.controllerKey = 400; * floppy.controllerKeySpecified = true; * floppy.connectable = _ci_floppy; * _dcs_floppy.device = floppy; * _cs_floppy.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_floppy }; * ManagedObjectReference _task_floppy = _service.ReconfigVM_Task(oComputer, _cs_floppy); * TaskInfo _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * while (_info_floppy.state == TaskInfoState.running) * _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * if (_info_floppy.state == TaskInfoState.success) * strResult += "Floppy Drive Created<br/>"; * else * strError = "Floppy Drive Was Not Created"; */ } if ((intStep == 100 || intStep == 6) && strError == "") { // 6) Attach CD-ROM Drive VirtualMachineConfigSpec _cs_cd = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec _dcs_cd = new VirtualDeviceConfigSpec(); _dcs_cd.operation = VirtualDeviceConfigSpecOperation.add; _dcs_cd.operationSpecified = true; VirtualDeviceConnectInfo _ci_cd = new VirtualDeviceConnectInfo(); _ci_cd.startConnected = false; VirtualCdrom cd = new VirtualCdrom(); VirtualCdromRemotePassthroughBackingInfo cdBack = new VirtualCdromRemotePassthroughBackingInfo(); cdBack.exclusive = false; cdBack.deviceName = ""; cd.backing = cdBack; cd.key = 3000; cd.controllerKey = 200; cd.controllerKeySpecified = true; cd.connectable = _ci_cd; _dcs_cd.device = cd; _cs_cd.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_cd }; ManagedObjectReference _task_cd = _service.ReconfigVM_Task(oComputer, _cs_cd); TaskInfo _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); while (_info_cd.state == TaskInfoState.running) { _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); } if (_info_cd.state == TaskInfoState.success) { strResult += "CD-ROM Was Created<br/>"; } else { strError = "CD-ROM Was Not Created"; } } if ((intStep == 100 || intStep == 7) && strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if ((intStep == 100 || intStep == 8) && strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if ((intStep == 100 || intStep == 9) && strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if ((intStep == 100 || intStep == 10) && strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
private void doAddVirtualSwitch() { ManagedObjectReference dcmor; ManagedObjectReference hostfoldermor; ManagedObjectReference hostmor = null; datacenter = cb.get_option("datacenter"); host = cb.get_option("host"); vswitchId = cb.get_option("vswitchid"); try { if (((datacenter != null) && (host != null)) || ((datacenter != null) && (host == null))) { dcmor = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", datacenter); if (dcmor == null) { Console.WriteLine("Datacenter not found"); return; } hostfoldermor = vmUtils.getHostFolder(dcmor); hostmor = vmUtils.getHost(hostfoldermor, host); } else if ((datacenter == null) && (host != null)) { hostmor = vmUtils.getHost(null, host); } if (hostmor != null) { Object cmobj = cb.getServiceUtil().GetDynamicProperty(hostmor, "configManager"); HostConfigManager configMgr = (HostConfigManager)cmobj; ManagedObjectReference nwSystem = configMgr.networkSystem; HostVirtualSwitchSpec spec = new HostVirtualSwitchSpec(); spec.numPorts = 8; cb.getConnection()._service.AddVirtualSwitch(nwSystem, vswitchId, spec); Console.WriteLine(cb.getAppName() + " : Successful creating : " + vswitchId); } else { Console.WriteLine("Host not found"); } } catch (SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault")) { Console.WriteLine(cb.getAppName() + "vswitchName exceeds the maximum " + "allowed length, or the number of ports " + "specified falls out of valid range, or the network " + "policy is invalid, or beacon configuration is invalid. "); } else if (e.Detail.FirstChild.LocalName.Equals("AlreadyExistsFault")) { Console.WriteLine(cb.getAppName() + " : Failed : Switch already exists "); } else if (e.Detail.FirstChild.LocalName.Equals("HostConfigFault")) { Console.WriteLine(cb.getAppName() + " : Failed : Configuration failures. "); } else if (e.Detail.FirstChild.LocalName.Equals("NotFoundFault")) { Console.WriteLine(e.Message.ToString()); } else { throw e; } } catch (Exception e) { Console.WriteLine(cb.getAppName() + " : Failed adding switch: " + vswitchId); throw e; } }
public object Collect(string vcentername, string url, string username, string password) { if (_service != null) { Disconnect(); } //###################setup xml file################ XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); //add root element XmlElement xmlroot = xmldoc.CreateElement("", vcentername, ""); xmldoc.AppendChild(xmlroot); //################################################### ArrayList ObjectList = new ArrayList(); _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); } TraversalSpec rpToRp = new TraversalSpec(); rpToRp.type = "ResourcePool"; rpToRp.path = "resourcePool"; rpToRp.skip = false; rpToRp.name = "rpToRp"; rpToRp.selectSet = new SelectionSpec[] { new SelectionSpec(), new SelectionSpec() }; rpToRp.selectSet[0].name = "rpToRp"; rpToRp.selectSet[1].name = "rpToVm"; TraversalSpec rpToVm = new TraversalSpec(); rpToVm.type = "ResourcePool"; rpToVm.path = "vm"; rpToVm.skip = false; rpToVm.name = "rpToVm"; rpToVm.selectSet = new SelectionSpec[] { }; TraversalSpec crToRp = new TraversalSpec(); crToRp.type = "ComputeResource"; crToRp.path = "resourcePool"; crToRp.skip = false; crToRp.name = "crToRp"; crToRp.selectSet = new SelectionSpec[] { rpToRp, new SelectionSpec() }; crToRp.selectSet[1].name = "rpToVm"; TraversalSpec crToH = new TraversalSpec(); crToH.type = "ComputeResource"; crToH.path = "host"; crToH.skip = false; crToH.name = "crToH"; crToH.selectSet = new SelectionSpec[] { }; TraversalSpec dcToHf = new TraversalSpec(); dcToHf.type = "Datacenter"; dcToHf.path = "hostFolder"; dcToHf.skip = false; dcToHf.name = "dcToHf"; dcToHf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToHf.selectSet[0].name = "visitFolders"; TraversalSpec dcToVmf = new TraversalSpec(); dcToVmf.type = "Datacenter"; dcToVmf.path = "vmFolder"; dcToVmf.skip = false; dcToVmf.name = "dcToVmf"; dcToVmf.selectSet = new SelectionSpec[] { new SelectionSpec() }; dcToVmf.selectSet[0].name = "visitFolders"; TraversalSpec HToVm = new TraversalSpec(); HToVm.type = "HostSystem"; HToVm.path = "vm"; HToVm.skip = false; HToVm.name = "HToVm"; HToVm.selectSet = new SelectionSpec[] { new SelectionSpec() }; HToVm.selectSet[0].name = "visitFolders"; TraversalSpec visitFolders = new TraversalSpec(); visitFolders.type = "Folder"; visitFolders.path = "childEntity"; visitFolders.skip = false; visitFolders.name = "visitFolders"; visitFolders.selectSet = new SelectionSpec[] { new SelectionSpec(), dcToHf, crToH, crToRp, rpToVm }; visitFolders.selectSet[0].name = "visitFolders"; TraversalSpec tSpec = default(TraversalSpec); tSpec = visitFolders; PropertySpec[] propSpecArray = null; propSpecArray = new PropertySpec[] { new PropertySpec() }; propSpecArray[0].type = "Datacenter"; propSpecArray[0].all = true; propSpecArray[0].allSpecified = true; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = propSpecArray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = _sic.rootFolder; spec.objectSet[0].skip = false; spec.objectSet[0].selectSet = new SelectionSpec[] { tSpec }; ObjectContent[] ocary = _service.RetrieveProperties(_propCol, new PropertyFilterSpec[] { spec }); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (Int32 oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; moref = mor.Value.ToString(); pcary = oc.propSet; //string vmname =""; for (Int32 propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("hostFolder"))) { XmlElement xmldcmoref = xmldoc.CreateElement("", "Datacenter", ""); XmlAttribute newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = moref; xmldcmoref.Attributes.Append(newAtt); xmldoc.ChildNodes.Item(1).AppendChild(xmldcmoref); folder = ((VimyyApi.ManagedObjectReference)(pc.val)).Value; XmlElement xmlfolder = xmldoc.CreateElement(null, "Folder", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Datacenter[@moref='" + moref + "']"); newAtt = xmldoc.CreateAttribute("moref"); newAtt.Value = folder; xmlfolder.Attributes.Append(newAtt); xmlnode3.AppendChild(xmlfolder); } if ((pc.name.Equals("name"))) { name = (pc.val.ToString()); XmlElement xmldcname = xmldoc.CreateElement(null, "DCname", null); XmlNode xmlnode3 = xmldoc.SelectSingleNode("//Datacenter[@moref='" + moref + "']"); XmlAttribute newAtt = xmldoc.CreateAttribute("DCname"); newAtt.Value = name; xmldcname.Attributes.Append(newAtt); xmlnode3.AppendChild(xmldcname); } } } } else { //("No Managed Entities retrieved!"); } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("Inventory.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); return(ObjectList); }
public abstract Task <VmNetwork[]> GetVmNetworks(ManagedObjectReference managedObjectReference);
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); Variables oVariable = new Variables(999); string strName = "healyTest"; string strCluster = "CLESVTLAB01"; double dblDriveC = 60.00; string strDatastore = "CTVXN00007"; double dblDrive2 = 10.00; double dblDrive3 = 10.00; string strPortGroupName = "dvPortGroup5"; // DHCP enabled string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_STD"; string strMDTbuildDB = "ServerShare"; string strVMguestOS = "windows7Server64Guest"; string strMACAddress = ""; string strResourcePool = ""; string strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", 999, "PNC-TestLab"); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); // Create computer ManagedObjectReference oComputer = null; oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } if (strError == "") { // 2) SCSI Controller 1 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(0, 2, 1000); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDriveC.ToString(), 0, 1000, ""); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 1 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 1 Was Not Created"; } } if (strError == "") { // 4) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive2.ToString(), 1, 1000, "_2"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } if (strError == "") { // 5) SCSI Controller 2 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(1, 3, 1001); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 6) Create Hard Disk 3 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive3 = dblDrive3 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive3.ToString(), 0, 1001, "_3"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 3 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 3 Was Not Created"; } } if (String.IsNullOrEmpty(Request.QueryString["build"]) == false) { if (strError == "") { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } if (strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if (strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if (strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if (strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
static int Dump(DumpOptions options) { try { //Connect to target Connect(options.url, options.username, options.password, null); //Find target VM vm = GetTargetVM(options.targetvm); if (vm is null) { Error(new Exception("Failed to find target VM " + options.targetvm + ", are you sure the name is right?")); } //Create Snapshot if specified, otherwise find existing one ManagedObjectReference snapshot = GetSnapshot(options.targetvm, options.snapshot); //Get information about the snapshot VirtualMachineFileInfo fileInfo = GetProperty <VirtualMachineConfigInfo>(snapshot, "config").files; //Build the objects we need ManagedObjectReference environmentBrowser = GetProperty <ManagedObjectReference>(vm, "environmentBrowser"); ManagedObjectReference datastoreBrowser = GetProperty <ManagedObjectReference>(environmentBrowser, "datastoreBrowser"); //Search for a vmem file ManagedObjectReference task = vim.SearchDatastore_Task(datastoreBrowser, fileInfo.snapshotDirectory, GetHostDatastoreBrowserSearchSpec()); TaskInfo info = GetProperty <TaskInfo>(task, "info"); string state = info.state.ToString(); while (state != "success") { switch (state) { case "error": Error(new Exception("Error searching datastore for snapshot files")); break; case "running": Thread.Sleep(1000); break; } state = GetProperty <TaskInfo>(task, "info").state.ToString(); } HostDatastoreBrowserSearchResults results = (HostDatastoreBrowserSearchResults)GetProperty <TaskInfo>(task, "info").result; //Check at least one vmem exists, which it may not if not using --snapshot FileInfo latestFile = null; if (results.file.Length == 0) { Error(new Exception("Failed to find any .vmem files associated with the VM, despite there being snapshots. Virtual machine memory may not have been captured. Recommend rerunning with --snapshot")); } //Grab the latest .vmem file if there is more than one associated with a VM foreach (FileInfo file in results.file) { if (latestFile == null || DateTime.Compare(file.modification, latestFile.modification) > 0) { latestFile = file; } } //Build the URLs to download directly from datastore string host = options.url.Remove(options.url.Length - 4); string dsName = FindTextBetween(results.folderPath, "[", "]"); string folderPath = results.folderPath.Remove(0, dsName.Length + 3); string vmemURL = host + "/folder/" + folderPath + latestFile.path + "?dcPath=" + datacenterName + "&dsName=" + dsName; string vmsnURL = host + "/folder/" + folderPath + latestFile.path.Replace(".vmem", ".vmsn") + "?dcPath=" + datacenterName + "&dsName=" + dsName; string vmemFile = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName(); string vmsnFile = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName(); string zipFile = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName(); //Make the web requests using (var client = new System.Net.WebClient()) { client.Credentials = new System.Net.NetworkCredential(options.username, options.password); client.Headers.Set(System.Net.HttpRequestHeader.ContentType, "application/octet-stream"); client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); Log("[x] Downloading " + latestFile.path + " (" + latestFile.fileSize / 1048576 + @"MB) to " + vmemFile + "..."); client.DownloadFile(vmemURL, vmemFile); Log("[x] Downloading " + latestFile.path.Replace(".vmem", ".vmsn") + " to " + vmsnFile + "..."); client.DownloadFile(vmsnURL, vmsnFile); } //Zip up the two downloaded files Log("[x] Download complete, grab the files " + vmemFile + " and " + vmsnFile); //Zipping not supported in .NET4.0, TODO: reimplment /* var zip = ZipFile.Open(zipFile, ZipArchiveMode.Create); * zip.CreateEntryFromFile(vmemFile, Path.GetFileName(vmemFile), CompressionLevel.Optimal); * zip.CreateEntryFromFile(vmsnFile, Path.GetFileName(vmsnFile), CompressionLevel.Optimal); * zip.Dispose(); * File.Delete(vmemFile); * File.Delete(vmsnFile); * System.IO.FileInfo zipFileInfo = new System.IO.FileInfo(zipFile); * Log("[x] Zipping complete, download " + zipFile + " (" + zipFileInfo.Length / 1048576 + "MB), rename to .zip, and follow instructions to use with Mimikatz");*/ //Delete the snapshot we created if needed if (options.snapshot) { Log("[x] Deleting the snapshot we created"); vim.RemoveSnapshot_Task(snapshot, false, true); } } catch (Exception fault) { Error(fault); } return(0); }
static void Connect(string url, string username, string password, string ip) { try { //Disable SSL Log("[x] Disabling SSL checks in case vCenter is using untrusted/self-signed certificates"); System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); //Create the vCenter API object Log("[x] Creating vSphere API interface"); binding = new System.ServiceModel.BasicHttpBinding { AllowCookies = true, MaxReceivedMessageSize = MAX_MESSAGE_SIZE, MaxBufferPoolSize = MAX_MESSAGE_SIZE, MaxBufferSize = MAX_MESSAGE_SIZE, ReaderQuotas = { MaxStringContentLength = MAX_MESSAGE_SIZE, MaxArrayLength = MAX_MESSAGE_SIZE, MaxDepth = MAX_MESSAGE_SIZE, MaxBytesPerRead = MAX_MESSAGE_SIZE } }; binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport; ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); var endpoint = new System.ServiceModel.EndpointAddress(url); vim = new VimPortTypeClient(binding, endpoint); var moref = new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance", }; //Bind to vCenter serviceContent = vim.RetrieveServiceContent(moref); Log("[x] Connected to " + serviceContent.about.fullName); //Attempt login if (username != null && password != null) { //Login with username and password Log("[x] Authenticating with provided username and password"); userSession = vim.Login(serviceContent.sessionManager, username, password, null); } else { //SspiHelper from https://github.com/m1chaeldg/vSphereSdkSspiSample string host = new Uri(url).Host; string domain = Environment.UserDomainName; Log("[x] Authenticating with SSPI token of executing user"); userSession = vim.LoginBySSPI(serviceContent.sessionManager, GetSspiToken("host/" + host + "@" + domain), null); } if (userSession is null) { Error(new Exception("Failed to authenticate.")); } Log("[x] Successfully authenticated"); //Retrieve filemanager guestFileManager = GetProperty <ManagedObjectReference>(serviceContent.guestOperationsManager, "fileManager"); if (guestFileManager is null) { Error(new Exception("Failed to retrieve filemanager")); } //Get the current session and check it's valid UserSession currentSession = GetProperty <UserSession>(serviceContent.sessionManager, "currentSession"); if (currentSession is null || currentSession.key != userSession.key) { Error(new Exception("Failed to retrieve current session")); } //Retrieve target VM if (ip != null) { vm = vim.FindByIp(serviceContent.searchIndex, null, ip, true); if (vm == null) { Error(new Exception("Cannot find target VM by IP")); } } } catch (Exception fault) //Generic catch all { Error(fault); } }
public static void Main(String[] args) { VMSnapshot obj = new VMSnapshot(); cb = AppUtil.AppUtil.initialize("VMSnapshot" , VMSnapshot.constructOptions() , args); Boolean valid = obj.customValidation(); if (valid) { cb.connect(); String vmName = cb.get_option("vmname"); ManagedObjectReference vmMor = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); if (vmMor != null) { String op = cb.get_option("operation"); Boolean res = false; if (op.Equals("create")) { res = obj.createSnapshot(vmMor); } else if (op.Equals("list")) { res = obj.listSnapshot(vmMor); } else if (op.Equals("revert")) { res = obj.revertSnapshot(vmMor); } else if (op.Equals("removeall")) { res = obj.removeAllSnapshot(vmMor); if (!res) { Console.WriteLine("Operation " + op + " cannot be performed."); } } else if (op.Equals("remove")) { res = obj.removeSnapshot(vmMor); } else { Console.WriteLine("Invalid operation" + op.ToString() + ". Valid Operations are [create|list|revert|remoeveall|remove]"); cb.disConnect(); Console.WriteLine("Press any key to exit: "); Console.Read(); Environment.Exit(1); } if (res) { Console.WriteLine("Operation " + op + " completed sucessfully"); } } else { Console.WriteLine("No VM " + vmName + " found"); } cb.disConnect(); } else { Console.WriteLine("Operation can not be performed"); } Console.WriteLine("Press any key to exit: "); Console.Read(); Environment.Exit(1); }
public static bool IsInPool(this ObjectContent content, ManagedObjectReference pool) { ManagedObjectReference mor = content.GetProperty("resourcePool") as ManagedObjectReference; return(mor != null && mor.Value == pool.Value); }
public bool DeleteManagedEntity() { cb.connect(); bool deleteResult = false; try { ManagedObjectReference memor = cb.getServiceUtil().GetDecendentMoRef(null, "ManagedEntity", this.GetMeName()); if (memor == null) { var errorMessage = string.Format( "Unable to find a managed entity named '{0}' in Inventory", this.GetMeName()); Console.WriteLine(errorMessage); log.LogLine(errorMessage); return(false); } ManagedObjectReference taskmor = cb.getConnection()._service.Destroy_Task(memor); // If we get a valid task reference, monitor the task for success or failure // and report task completion or failure. if (taskmor != null) { Object[] result = cb.getServiceUtil().WaitForValues( taskmor, new String[] { "info.state", "info.error" }, 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)) { log.LogLine(cb.getAppName() + " : Successful delete of Managed Entity : " + this.GetMeName()); deleteResult = true; } else { log.LogLine(cb.getAppName() + " : Failed delete of Managed Entity : " + this.GetMeName()); if (result.Length == 2 && result[1] != null) { if (result[1].GetType().Equals("MethodFault")) { cb.getUtil().LogException((Exception)result[1]); } } } } } catch (Exception e) { cb.getUtil().LogException(e); log.LogLine(cb.getAppName() + " : Failed delete of Managed Entity : " + this.GetMeName()); throw e; } finally { cb.disConnect(); } return(deleteResult); }
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(); } }
/** * Delete a Scheduled Task * * @param oneTimeTask the ManagedObjectReference of task to delete * @ */ private void deleteScheduledTask(ManagedObjectReference oneTimeTask) { try { // Remove the One Time Scheduled Task _service.RemoveScheduledTask(oneTimeTask); Console.WriteLine("Successfully Deleted ScheduledTask: " + cb.get_option("taskname")); } catch(SoapException e){ Console.WriteLine(" InvalidRequest: Task Name may be wrong"); } catch(Exception e){ Console.WriteLine("Error"); e.StackTrace.ToString(); } }
/// <summary> /// Method to create Storage DRSgroup /// </summary> private void CreateSDRS() { string dcName = cb.get_option("dcname"); string drsname = cb.get_option("sdrsname"); string behavior = cb.get_option("behavior"); string loadBalanceInterval = cb.get_option("loadbalinterval"); string dsname = cb.get_option("datastore"); ManagedObjectReference storagePod = new ManagedObjectReference(); ManagedObjectReference storageResourceManager = cb._connection._sic.storageResourceManager; ManagedObjectReference dcmor = cb._svcUtil.getEntityByName("Datacenter",dcName); if (dcmor != null) { ManagedObjectReference datastoreFolder = cb.getServiceUtil().GetMoRefProp (dcmor, "datastoreFolder"); storagePod = cb.getConnection()._service.CreateStoragePod(datastoreFolder, drsname); Console.WriteLine("Success: Creating storagePod."); StorageDrsConfigSpec sdrsConfigSpec = GetStorageDrsConfigSpec(behavior, loadBalanceInterval); ManagedObjectReference taskmor = cb.getConnection()._service.ConfigureStorageDrsForPod_Task(storageResourceManager, storagePod, sdrsConfigSpec, true); if (taskmor != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("Sucessfully configured storage pod" + drsname); } else { Console.WriteLine("Failure: Configuring storagePod"); throw new Exception(status); } } if (dsname != null) { ManagedObjectReference dsMoref = cb._svcUtil.getEntityByName("Datastore", dsname); if (dsMoref != null) { ManagedObjectReference[] dslist = new ManagedObjectReference[] { dsMoref }; ManagedObjectReference task = cb.getConnection()._service. MoveIntoFolder_Task(storagePod, dslist); if (task != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("\nSuccess: Adding datastore to storagePod."); } else { Console.WriteLine("Failure: Adding datastore to storagePod."); throw new Exception(status); } } } else { throw new Exception("Datastore" + dsname + "not found"); } } } else { throw new Exception("datacenter" + dcName + "not found"); } }
public static string AsString(this ManagedObjectReference mor) { return($"{mor.type}|{mor.Value}"); }
private void doRealTime() { ManagedObjectReference vmmor = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", cb.get_option("vmname")); if (vmmor != null) { ManagedObjectReference pmRef = cb.getConnection()._sic.perfManager; PerfCounterInfo[] cInfo = (PerfCounterInfo[])cb.getServiceUtil().GetDynamicProperty(pmRef, "perfCounter"); ArrayList vmCpuCounters = new ArrayList(); for (int i = 0; i < cInfo.Length; ++i) { if ("cpu".Equals(cInfo[i].groupInfo.key)) { vmCpuCounters.Add(cInfo[i]); } } Hashtable counters = new Hashtable(); while (true) { int index = 0; for (IEnumerator it = vmCpuCounters.GetEnumerator(); it.MoveNext();) { PerfCounterInfo pcInfo = (PerfCounterInfo)it.Current; Console.WriteLine(++index + " - " + pcInfo.nameInfo.summary); } index = cb.getUtil().getIntInput("Please select a counter from" + " the above list" + "\nEnter 0 to end: ", 1); if (index > vmCpuCounters.Count || index <= 0) { Console.WriteLine("*** Value out of range!"); } else { --index; if (index < 0) { return; } PerfCounterInfo pcInfo = (PerfCounterInfo)vmCpuCounters[index]; counters.Add((pcInfo.key), pcInfo); break; } } PerfMetricId[] aMetrics = cb.getConnection()._service.QueryAvailablePerfMetric(pmRef, vmmor, DateTime.MinValue, false, DateTime.MaxValue, false, 20, true); ArrayList mMetrics = new ArrayList(); if (aMetrics != null) { for (int index = 0; index < aMetrics.Length; ++index) { if (counters.ContainsKey(aMetrics[index].counterId)) { mMetrics.Add(aMetrics[index]); } } } if (mMetrics.Count > 0) { monitorPerformance(pmRef, vmmor, mMetrics, counters); } else { Console.WriteLine("Data for selected counter is not available"); } } else { Console.WriteLine("Virtual Machine " + cb.get_option("vmname") + " not found"); } }
/** * Use the SearchIndex to find a VirtualMachine by Inventory Path * * @ */ private void findVirtualMachine() { String vmPath = cb.get_option("vmpath"); _virtualMachine = _service.FindByInventoryPath(_searchIndex, vmPath); }
/// <summary> /// Create object of OvfCreateImportSpecParams /// </summary> /// <param name="host">ManagedObjectReference</param> /// <param name="newVmName">string</param> /// <returns>OvfCreateImportSpecParams</returns> private OvfCreateImportSpecParams createImportSpecParams( ManagedObjectReference host, string newVmName) { OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams(); importSpecParams.hostSystem = host; importSpecParams.locale = ""; importSpecParams.entityName = newVmName; importSpecParams.deploymentOption = ""; return importSpecParams; }
public static Object getObjectProperty(ManagedObjectReference moRef, String propertyName) { return(getProperties(moRef, new String[] { propertyName })[0]); }
/// <summary> /// Return MOR /// </summary> /// <param name="folder">ManagedObjectReference</param> /// <param name="type">string</param> /// <param name="name">string</param> /// <returns>ManagedObjectReference</returns> public ManagedObjectReference GetMOREFsInFolderByType(ManagedObjectReference folder, string type, string name) { String propName = "name"; string[] type1 = new string[2]; type1[0] = type; ManagedObjectReference viewManager = cb._connection._sic.viewManager; ManagedObjectReference containerView = cb._connection._service.CreateContainerView(viewManager, folder, type1, true); PropertySpec propertySpec = new PropertySpec(); propertySpec.all = false; propertySpec.type = type; propertySpec.pathSet = new string[] { propName }; TraversalSpec ts = new TraversalSpec(); ts.name = "view"; ts.path = "view"; ts.skip = false; ts.type = "ContainerView"; // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.obj = containerView; objectSpec.skip = true; objectSpec.selectSet = new SelectionSpec[] { ts }; // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.propSet = new PropertySpec[] { propertySpec }; propertyFilterSpec.objectSet = new ObjectSpec[] { objectSpec }; PropertyFilterSpec[] filterspec = new PropertyFilterSpec[3]; filterspec[0] = propertyFilterSpec; ObjectContent[] ocary = cb._svcUtil.retrievePropertiesEx(cb._connection._sic.propertyCollector, filterspec); if (ocary == null || ocary.Length == 0) { return null; } ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] propary = null; string propval = null; bool found = false; for (int oci = 0; oci < ocary.Length && !found; oci++) { oc = ocary[oci]; mor = oc.obj; propary = oc.propSet; if ((type == null) || (type != null && cb._svcUtil.typeIsA(type, mor.type))) { if (propary.Length > 0) { propval = (string)propary[0].val; } found = propval != null && name.Equals(propval); propval = null; } } if (!found) { mor = null; } return mor; }
protected void Page_Load(object sender, EventArgs e) { AuthenticateUser(); if (Request.Cookies["profileid"] != null && Request.Cookies["profileid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); } if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } oDataPoint = new DataPoint(intProfile, dsn); oUser = new Users(intProfile, dsn); oServer = new Servers(intProfile, dsn); oAsset = new Asset(intProfile, dsnAsset); oForecast = new Forecast(intProfile, dsn); oPlatform = new Platforms(intProfile, dsn); oType = new Types(intProfile, dsn); oModel = new Models(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oIPAddresses = new IPAddresses(intProfile, dsnIP, dsn); oFunction = new Functions(intProfile, dsn, intEnvironment); oOperatingSystem = new OperatingSystems(intProfile, dsn); oServicePack = new ServicePacks(intProfile, dsn); oClass = new Classes(intProfile, dsn); oEnvironment = new Environments(intProfile, dsn); if (oUser.IsAdmin(intProfile) == true || (oDataPoint.GetPagePermission(intApplication, "ASSET") == true || intDataPointAvailableAsset == 1)) { panAllow.Visible = true; if (Request.QueryString["save"] != null) { panSave.Visible = true; } if (Request.QueryString["error"] != null) { panError.Visible = true; // -100: More than one device name // -10: No device names // -5: Improper Name Format // -1: ServerID = 0 if (Request.QueryString["error"] == "-100") { lblError.Text = "More than one name"; } else if (Request.QueryString["error"] == "-10") { lblError.Text = "User Cancelled Prompt"; } else if (Request.QueryString["error"] == "-5") { lblError.Text = "Name is in Incorrect Format"; } else if (Request.QueryString["error"] == "-1") { lblError.Text = "DeviceID = 0"; } else { lblError.Text = "Generic Error"; } } Int32.TryParse(oFunction.decryptQueryString(Request.QueryString["id"]), out intID); if (Request.QueryString["close"] != null) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "close", "<script type=\"text/javascript\">window.close();<" + "/" + "script>"); } else if (intID > 0) { DataSet ds = oDataPoint.GetAsset(intID); if (ds.Tables[0].Rows.Count == 1) { // Load General Information intAsset = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); lblAssetID.Text = "#" + intAsset.ToString(); string strSerial = ds.Tables[0].Rows[0]["serial"].ToString(); string strAsset = ds.Tables[0].Rows[0]["asset"].ToString(); string strHeader = (strSerial.Length > 15 ? strSerial.Substring(0, 15) + "..." : strSerial); lblHeader.Text = """ + strHeader.ToUpper() + """; Master.Page.Title = "DataPoint | VMware (" + strHeader + ")"; lblHeaderSub.Text = "Provides all the information about a VMware guest..."; int intMenuTab = 0; if (Request.QueryString["menu_tab"] != null && Request.QueryString["menu_tab"] != "") { intMenuTab = Int32.Parse(Request.QueryString["menu_tab"]); } Tab oTab = new Tab(hdnTab.ClientID, intMenuTab, "divMenu1", true, false); oTab.AddTab("Asset Information", ""); oTab.AddTab("Host Information", ""); oTab.AddTab("Resource Dependencies", ""); oTab.AddTab("Provisioning Information", ""); //oTab.AddTab("Network Adapter Configuration", ""); strMenuTab1 = oTab.GetTabs(); if (!IsPostBack) { //DataSet dsAssets = oServer.GetAsset(intAsset); //foreach (DataRow drAsset in dsAssets.Tables[0].Rows) //{ // if (drAsset["latest"].ToString() == "1") // { // intAsset = Int32.Parse(drAsset["assetid"].ToString()); // intAssetClass = Int32.Parse(drAsset["classid"].ToString()); // intAssetEnv = Int32.Parse(drAsset["environmentid"].ToString()); // break; // } //} // Asset Information oDataPoint.LoadTextBox(txtPlatformSerial, intProfile, null, "", lblPlatformSerial, fldPlatformSerial, "VMWARE_SERIAL", strSerial, "", false, true); oDataPoint.LoadTextBox(txtPlatformAsset, intProfile, null, "", lblPlatformAsset, fldPlatformAsset, "VMWARE_ASSET", strAsset, "", false, true); int intAssetAttribute = 0; Int32.TryParse(oAsset.Get(intAsset, "asset_attribute"), out intAssetAttribute); oDataPoint.LoadDropDown(ddlAssetAttribute, intProfile, null, "", lblAssetAttribute, fldAssetAttribute, "ASSET_ATTRIBUTE", "Name", "AttributeId", oAsset.getAssetAttributes(null, "", 1), intAssetAttribute, true, false, false); oDataPoint.LoadTextBox(txtAssetAttributeComment, intProfile, null, "", lblAssetAttributeComment, fldAssetAttributeComment, "ASSET_ATTRIBUTE_COMMENT", oAsset.getAssetAttributesComments(intAsset), "", false, true); ddlAssetAttribute.Attributes.Add("onclick", "return SetControlsForAssetAttributes()"); ddlPlatform.Attributes.Add("onchange", "PopulatePlatformTypes('" + ddlPlatform.ClientID + "','" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformType.Attributes.Add("onchange", "PopulatePlatformModels('" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModel.Attributes.Add("onchange", "PopulatePlatformModelProperties('" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModelProperty.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformModelProperty.ClientID + "','" + hdnModel.ClientID + "');"); int intModel = 0; Int32.TryParse(oAsset.Get(intAsset, "modelid"), out intModel); hdnModel.Value = intModel.ToString(); int intModelParent = 0; Int32.TryParse(oModelsProperties.Get(intModel, "modelid"), out intModelParent); int intType = oModel.GetType(intModelParent); int intPlatform = oType.GetPlatform(intType); oDataPoint.LoadDropDown(ddlPlatform, intProfile, null, "", lblPlatform, fldPlatform, "VMWARE_PLATFORM", "name", "platformid", oPlatform.Gets(1), intPlatform, false, false, true); oDataPoint.LoadDropDown(ddlPlatformType, intProfile, null, "", lblPlatformType, fldPlatformType, "VMWARE_TYPE", "name", "id", oType.Gets(intPlatform, 1), intType, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModel, intProfile, null, "", lblPlatformModel, fldPlatformModel, "VMWARE_MODEL", "name", "id", oModel.Gets(intType, 1), intModelParent, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModelProperty, intProfile, null, "", lblPlatformModelProperty, fldPlatformModelProperty, "VMWARE_MODEL_PROP", "name", "id", oModelsProperties.GetModels(0, intModelParent, 1), intModel, false, false, true); // Get Asset DataSet dsAsset = oAsset.GetGuest(intAsset); if (dsAsset.Tables[0].Rows.Count > 0) { oDataPoint.LoadTextBoxDeviceName(txtName, btnName, null, true, hdnPNC, intProfile, btnNameLookup, "/datapoint/asset/datapoint_asset_search.aspx?t=name&q=" + oFunction.encryptQueryString(dsAsset.Tables[0].Rows[0]["name"].ToString()), lblName, fldName, "VMWARE_NAME", dsAsset.Tables[0].Rows[0]["name"].ToString(), "", false, false); if (txtName.Text != "") { lblHeader.Text += " [" + txtName.Text + "]"; } lblStatus.Text = dsAsset.Tables[0].Rows[0]["statusname"].ToString(); int intClass = Int32.Parse(dsAsset.Tables[0].Rows[0]["classid"].ToString()); int intEnv = Int32.Parse(dsAsset.Tables[0].Rows[0]["environmentid"].ToString()); hdnEnvironment.Value = intEnv.ToString(); oDataPoint.LoadDropDown(ddlPlatformClass, intProfile, null, "", lblPlatformClass, fldPlatformClass, "VMWARE_CLASS", "name", "id", oClass.Gets(1), intClass, false, false, true); oDataPoint.LoadDropDown(ddlPlatformEnvironment, intProfile, null, "", lblPlatformEnvironment, fldPlatformEnvironment, "VMWARE_ENVIRONMENT", "name", "id", oClass.GetEnvironment(intClass, 0), intEnv, false, false, true); ddlStatus.SelectedValue = dsAsset.Tables[0].Rows[0]["status"].ToString(); ddlStatus.Enabled = (intAssetAttribute == (int)AssetAttribute.Ok); panStatus.Visible = (ddlStatus.Enabled == false); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } // Get Original Detail VMWare oVMWare = new VMWare(intProfile, dsn); DataSet dsGuest = oVMWare.GetGuest(dsAsset.Tables[0].Rows[0]["name"].ToString()); if (dsGuest.Tables[0].Rows.Count > 0) { panVMWare.Visible = true; DataRow drGuest = dsGuest.Tables[0].Rows[0]; int intDatastore = Int32.Parse(drGuest["datastoreid"].ToString()); lblBuildDataStore.Text = oVMWare.GetDatastore(intDatastore, "name"); int intHost = Int32.Parse(drGuest["hostid"].ToString()); lblBuildHost.Text = oVMWare.GetHost(intHost, "name"); int intCluster = Int32.Parse(oVMWare.GetHost(intHost, "clusterid")); lblBuildCluster.Text = oVMWare.GetCluster(intCluster, "name"); int intFolder = Int32.Parse(oVMWare.GetCluster(intCluster, "folderid")); lblBuildFolder.Text = oVMWare.GetFolder(intFolder, "name"); int intDataCenter = Int32.Parse(oVMWare.GetFolder(intFolder, "datacenterid")); lblBuildDataCenter.Text = oVMWare.GetDatacenter(intDataCenter, "name"); int intVirtualCenter = Int32.Parse(oVMWare.GetDatacenter(intDataCenter, "virtualcenterid")); lblBuildVirtualCenter.Text = oVMWare.GetVirtualCenter(intVirtualCenter, "name"); // Get Host if (Request.Cookies["host"] != null && Request.Cookies["host"].Value != "") { string strHost = ""; string strFind = txtName.Text; //strFind = "ohcleapp103d"; DateTime datStart = DateTime.Parse(Request.Cookies["host"].Value); Response.Cookies["host"].Value = ""; //VMWare oVMWare = new VMWare(intProfile, dsn); DataSet dsVirtualCenter = oVMWare.GetVirtualCenters(1); foreach (DataRow drVirtualCenter in dsVirtualCenter.Tables[0].Rows) { intVirtualCenter = Int32.Parse(drVirtualCenter["id"].ToString()); string strVirtualCenter = drVirtualCenter["name"].ToString(); string strVirtualCenterURL = drVirtualCenter["url"].ToString(); int intVirtualCenterEnv = Int32.Parse(drVirtualCenter["environment"].ToString()); DataSet dsDataCenter = oVMWare.GetDatacenters(intVirtualCenter, 1); foreach (DataRow drDataCenter in dsDataCenter.Tables[0].Rows) { intDataCenter = Int32.Parse(drDataCenter["id"].ToString()); string strDataCenter = drDataCenter["name"].ToString(); string strConnect = oVMWare.ConnectDEBUG(strVirtualCenterURL, intVirtualCenterEnv, strDataCenter); VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); try { ManagedObjectReference oVM = oVMWare.GetVM(strFind); GuestInfo ginfo = (GuestInfo)oVMWare.getObjectProperty(oVM, "guest"); lblGuestName.Text = ginfo.guestFullName; lblGuestState.Text = ginfo.guestState; GuestNicInfo[] nInfo = ginfo.net; foreach (GuestNicInfo nic in nInfo) { string[] strIPAddresses = nic.ipAddress; foreach (string strIPAddress in strIPAddresses) { if (lblIPAddress.Text != "") { lblIPAddress.Text += ", "; } lblIPAddress.Text += strIPAddress; } if (lblMACAddress.Text != "") { lblMACAddress.Text += ", "; } lblMACAddress.Text += nic.macAddress; if (lblNetwork.Text != "") { lblNetwork.Text += ", "; } lblNetwork.Text += nic.network; } VirtualMachineConfigInfo vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oVM, "config"); VirtualMachineSummary oVMSummary = (VirtualMachineSummary)oVMWare.getObjectProperty(oVM, "summary"); VirtualMachineConfigSummary oVMConfig = oVMSummary.config; lblRAM.Text = oVMConfig.memorySizeMB.ToString(); lblCPUs.Text = oVMConfig.numCpu.ToString(); lblPath.Text = oVMConfig.vmPathName; VirtualMachineRuntimeInfo oVMRuntime = oVMSummary.runtime; ManagedObjectReference oVMHost = oVMRuntime.host; strHost = (string)oVMWare.getObjectProperty(oVMHost, "name"); if (strHost.IndexOf(".") > -1) { strHost = strHost.Substring(0, strHost.IndexOf(".")); } lblVirtualCenter.Text = strVirtualCenter; lblDataCenter.Text = strDataCenter; break; } catch { } finally { if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } } } if (strHost != "") { oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(strHost), lblHostName, fldHostName, "VMWARE_HOST", strHost, "", false, false); } else { panHostNo.Visible = true; } TimeSpan oSpan = DateTime.Now.Subtract(datStart); btnHostQuery.Enabled = false; btnHostQuery.Text = "Query Time: " + oSpan.TotalSeconds.ToString("0") + " seconds..."; } else { txtHostName.Visible = false; lblHostName.Text = "---"; lblDataCenter.Text = "---"; lblVirtualCenter.Text = "---"; } oDataPoint.LoadPanel(panHostQuery, intProfile, fldHostQuery, "VMWARE_HOST_QUERY"); } else { Solaris oSolaris = new Solaris(intProfile, dsn); DataSet dsServers = oServer.GetAssetsAsset(intAsset); foreach (DataRow drServer in dsServers.Tables[0].Rows) { DataSet dsSVE = oSolaris.GetSVEGuest(Int32.Parse(drServer["serverid"].ToString())); if (dsSVE.Tables[0].Rows.Count > 0) { panSVE.Visible = true; int intCluster = Int32.Parse(dsSVE.Tables[0].Rows[0]["clusterid"].ToString()); lblSVECluster.Text = oSolaris.GetSVECluster(intCluster, "name"); } } } // Resource Dependencies AssetOrder oAssetOrder = new AssetOrder(0, dsn, dsnAsset, intEnvironment); Services oService = new Services(0, dsn); ServiceRequests oServiceRequest = new ServiceRequests(0, dsn); rptServiceRequests.DataSource = oAssetOrder.GetByAsset(intAsset, false); rptServiceRequests.DataBind(); trServiceRequests.Visible = (rptServiceRequests.Items.Count == 0); foreach (RepeaterItem ri in rptServiceRequests.Items) { Label lblServiceID = (Label)ri.FindControl("lblServiceID"); int intService = Int32.Parse(lblServiceID.Text); Label lblDetails = (Label)ri.FindControl("lblDetails"); Label lblProgress = (Label)ri.FindControl("lblProgress"); if (lblProgress.Text == "") { lblProgress.Text = "<i>Unavailable</i>"; } else { int intResource = Int32.Parse(lblProgress.Text); double dblAllocated = 0.00; double dblUsed = 0.00; int intStatus = 0; bool boolAssigned = false; DataSet dsResource = oDataPoint.GetServiceRequestResource(intResource); if (dsResource.Tables[0].Rows.Count > 0) { Int32.TryParse(dsResource.Tables[0].Rows[0]["status"].ToString(), out intStatus); } foreach (DataRow drResource in dsResource.Tables[1].Rows) { boolAssigned = true; dblAllocated += double.Parse(drResource["allocated"].ToString()); dblUsed += double.Parse(drResource["used"].ToString()); intStatus = Int32.Parse(drResource["status"].ToString()); } if (intStatus == (int)ResourceRequestStatus.Closed) { lblProgress.Text = oServiceRequest.GetStatusBar(100.00, "100", "12", true); } else if (intStatus == (int)ResourceRequestStatus.Cancelled) { lblProgress.Text = "Cancelled"; } else if (boolAssigned == false) { string strManager = ""; DataSet dsManager = oService.GetUser(intService, 1); // Managers foreach (DataRow drManager in dsManager.Tables[0].Rows) { if (strManager != "") { strManager += "\\n"; } int intManager = Int32.Parse(drManager["userid"].ToString()); strManager += " - " + oUser.GetFullName(intManager) + " [" + oUser.GetName(intManager) + "]"; } lblProgress.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"alert('This request is pending assignment by the following...\\n\\n" + strManager + "');\">Pending Assignment</a>"; } else if (dblAllocated > 0.00) { lblProgress.Text = oServiceRequest.GetStatusBar((dblUsed / dblAllocated) * 100.00, "100", "12", true); } else { lblProgress.Text = "<i>N / A</i>"; } lblDetails.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('/datapoint/service/resource.aspx?id=" + oFunction.encryptQueryString(intResource.ToString()) + "', '800', '600');\">" + lblDetails.Text + "</a>"; } } // Provioning History rptHistory.DataSource = oAsset.GetProvisioningHistory(oDataPoint.AssetHistorySelect(intAsset)); rptHistory.DataBind(); lblHistory.Visible = (rptHistory.Items.Count == 0); oDataPoint.LoadPanel(panProvisioning, intProfile, fldProvisioning, "VMWARE_STATUS"); } } else { if (Request.QueryString["t"] != null && Request.QueryString["q"] != null) { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&r=0"); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } } } else if (Request.QueryString["q"] != null && Request.QueryString["q"] != "") { string strQuery = oFunction.decryptQueryString(Request.QueryString["q"]); DataSet ds = oDataPoint.GetAssetName(strQuery, intID, 0, "", "", 0); if (ds.Tables[0].Rows.Count == 1) { intID = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); Response.Redirect(Request.Path + "?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&id=" + oFunction.encryptQueryString(intID.ToString())); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?multiple=true&t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"]); } } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } btnClose.Attributes.Add("onclick", "window.close();return false;"); btnPrint.Attributes.Add("onclick", "window.print();return false;"); btnName.Attributes.Add("onclick", "return OpenWindow('DEVICE_NAME','?assetid=" + intAsset.ToString() + "');"); btnSave.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); btnSaveClose.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); ddlPlatformClass.Attributes.Add("onchange", "PopulateEnvironments('" + ddlPlatformClass.ClientID + "','" + ddlPlatformEnvironment.ClientID + "',0);"); ddlPlatformEnvironment.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformEnvironment.ClientID + "','" + hdnEnvironment.ClientID + "');"); btnHostQuery.Attributes.Add("onclick", "ProcessButton(this,'Querying... please be patient...','225') && ProcessControlButton();"); } else { panDenied.Visible = true; } }
private void doRemoveVirtualSwitchPortGroup() { ManagedObjectReference dcmor; ManagedObjectReference hostfoldermor; ManagedObjectReference hostmor = null; datacenter = cb.get_option("datacenter"); host = cb.get_option("host"); portGroupName = cb.get_option("portgroupname"); try { if (((datacenter != null) && (host != null)) || ((datacenter != null) && (host == null))) { dcmor = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", datacenter); if (dcmor == null) { Console.WriteLine("Datacenter not found"); return; } hostfoldermor = vmUtils.getHostFolder(dcmor); hostmor = vmUtils.getHost(hostfoldermor, host); } else if ((datacenter == null) && (host != null)) { hostmor = vmUtils.getHost(null, host); } if (hostmor != null) { Object cmobj = cb.getServiceUtil().GetDynamicProperty(hostmor, "configManager"); HostConfigManager configMgr = (HostConfigManager)cmobj; ManagedObjectReference nwSystem = configMgr.networkSystem; HostNetworkInfo netInfo = (HostNetworkInfo)cb.getServiceUtil().GetDynamicProperty(nwSystem, "networkInfo"); cb.getConnection()._service.RemovePortGroup(nwSystem, portGroupName); Console.WriteLine(cb.getAppName() + " : Successful removing portgroup " + portGroupName); } else { Console.WriteLine("Host not found"); } } catch (SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("InvalidArgumentFault")) { Console.WriteLine(cb.getAppName() + " : Failed removing " + portGroupName); Console.WriteLine("PortGroup vlanId or network policy may be invalid .\n"); } else if (e.Detail.FirstChild.LocalName.Equals("NotFoundFault")) { Console.WriteLine(cb.getAppName() + " : Failed removing " + portGroupName); Console.WriteLine(" Switch or portgroup not found.\n"); } } catch (NullReferenceException e) { Console.WriteLine(cb.getAppName() + " : Failed removing " + portGroupName); Console.WriteLine("Datacenter or Host may be invalid \n"); throw e; } catch (Exception e) { Console.WriteLine(cb.getAppName() + " : Failed removing " + portGroupName); throw e; } }
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(); }
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 List <string> generateListOfVms() { List <string> vmList = new List <string>(); try { Console.WriteLine("Generating inventory list..."); BuildTypeInfo(); // Retrieve Contents recursively starting at the root folder // and using the default property collector. ObjectContent [] ocary = cb.getServiceUtil().GetContentsRecursively(null, null, typeInfo, true); ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty [] pcary = null; DynamicProperty pc = null; for (int oci = 0; oci < ocary.Length; oci++) { oc = ocary [oci]; mor = oc.obj; pcary = oc.propSet; if (!mor.type.Equals("VirtualMachine")) { continue; } cb.log.LogLine("Object Type : " + mor.type); cb.log.LogLine("Reference Value : " + mor.Value); if (pcary != null) { for (int pci = 0; pci < pcary.Length; pci++) { pc = pcary [pci]; if (!pc.name.Equals("name")) { continue; } cb.log.LogLine(" Property Name : " + pc.name); if (pc != null) { if (!pc.val.GetType().IsArray) { vmList.Add(pc.val + ""); cb.log.LogLine(" Property Value : " + pc.val); } else { Array ipcary = (Array)pc.val; cb.log.LogLine("Val : " + pc.val); for (int ii = 0; ii < ipcary.Length; ii++) { object oval = ipcary.GetValue(ii); if (oval.GetType().Name.IndexOf("ManagedObjectReference") >= 0) { ManagedObjectReference imor = (ManagedObjectReference)oval; cb.log.LogLine("Inner Object Type : " + imor.type); cb.log.LogLine("Inner Reference Value : " + imor.Value); } else { cb.log.LogLine("Inner Property Value : " + oval); } } } } } } } cb.log.LogLine("Done Printing Inventory"); cb.log.LogLine("Browser : Successful Getting Contents"); } catch (SoapException e) { Console.WriteLine("Browser : Failed Getting Contents"); Console.WriteLine("Encountered SoapException"); throw e; } catch (Exception e) { cb.log.LogLine("Browser : Failed Getting Contents"); throw e; } return(vmList); }
internal Cluster(IVimService vimService, ManagedObjectReference managedObject) : base(vimService, managedObject) { }
private void removePluginWorker_DoWork(object sender, DoWorkEventArgs e) { try { string hostName = vhostname; //#########################setup plugin in a xml file################### XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); //add root element XmlElement xmlroot = xmldoc.CreateElement("root"); xmldoc.AppendChild(xmlroot); //###################################################################### _service2 = new VimService(); _service2.Url = vurl; _svcRef2 = new ManagedObjectReference(); _svcRef2.type = "ServiceInstance"; _svcRef2.Value = "ServiceInstance"; _service2.CookieContainer = new System.Net.CookieContainer(); CreateServiceRef2("ServiceInstance"); _sic2 = _service2.RetrieveServiceContent(_svcRef2); _propCol2 = _sic2.propertyCollector; _rootFolder2 = _sic2.rootFolder; String userName = vusername; String password = vpassword; if (_sic2.sessionManager != null) { _service2.Login(_sic2.sessionManager, userName, password, null); ManagedObjectReference extMOREF = _sic2.extensionManager; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = new PropertySpec[] { new PropertySpec() }; spec.propSet[0].all = false; spec.propSet[0].allSpecified = spec.propSet[0].all; spec.propSet[0].type = extMOREF.type; spec.propSet[0].pathSet = new string[] { "extensionList" }; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = extMOREF; spec.objectSet[0].skip = false; ObjectContent[] ocary = _service2.RetrieveProperties(_sic2.propertyCollector, new PropertyFilterSpec[] { spec }); ArrayList ObjectList = new ArrayList(); if (ocary != null) { ObjectContent oc = null; ManagedObjectReference mor = null; DynamicProperty[] pcary = null; DynamicProperty pc = null; for (int oci = 0; oci <= ocary.Length - 1; oci++) { oc = ocary[oci]; mor = oc.obj; pcary = oc.propSet; for (int propi = 0; propi <= pcary.Length - 1; propi++) { pc = pcary[propi]; if ((pc.name.Equals("extensionList"))) { try { for (int pci = 0; ; pci++) { ObjectList.Add(((VimApi.Extension[])(pc.val))[pci].key); } } catch { // } string leftcharObjL; for (int olc = 0; olc < ObjectList.Count; olc++) { leftcharObjL = ObjectList[olc].ToString(); if (leftcharObjL.StartsWith("com.virtualizeplanet.")) { leftcharObjL = leftcharObjL.Remove(0, 21); //comboBox2.Items.Add(leftcharObjL); //comboBox2.SelectedIndex = 0; XmlElement xmldcmoref = xmldoc.CreateElement("", "PluginList", ""); XmlAttribute newAtt = xmldoc.CreateAttribute("Position"); newAtt.Value = leftcharObjL; xmldcmoref.Attributes.Append(newAtt); xmldoc.ChildNodes.Item(1).AppendChild(xmldcmoref); } } } } } } } XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineChars = Environment.NewLine + Environment.NewLine; XmlWriter xmlwrite = XmlWriter.Create("plugin.xml", xmlWriterSettings); xmldoc.Save(xmlwrite); xmlwrite.Close(); removePluginWorker.CancelAsync(); } catch { MessageBox.Show("Something maybe wrong with your settings"); } }
private void registerPluginWorker_DoWork(object sender, DoWorkEventArgs 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; string userName = vusername; string password = vpassword; string companyStr = textBox4.Text; string descStr = textBox3.Text; string keyStr = "com.virtualizeplanet." + textBox2.Text; string ext_url = pluginUrl; string adminEmail = "*****@*****.**"; string versionStr = "4.0"; Description description = new Description(); description.label = textBox3.Text; description.summary = descStr; ExtensionServerInfo esi = new ExtensionServerInfo(); esi.url = ext_url; esi.description = description; esi.company = companyStr; esi.type = "com.vmware.vim.viClientScripts"; //do not change; esi.adminEmail = new String[] { adminEmail }; ExtensionClientInfo eci = new ExtensionClientInfo(); eci.version = versionStr; eci.description = description; eci.company = companyStr; eci.type = "com.vmware.vim.viClientScripts"; eci.url = ext_url; Extension ext = new Extension(); ext.description = description; ext.key = keyStr; ext.version = versionStr; ext.subjectName = "blank"; ext.server = new ExtensionServerInfo[] { esi }; ext.client = new ExtensionClientInfo[] { eci }; ext.lastHeartbeatTime = DateTime.Now; if (_sic.sessionManager != null) { _service.Login(_sic.sessionManager, userName, password, null); ManagedObjectReference extMgrMof = _sic.extensionManager; _service.RegisterExtension(extMgrMof, ext); } MessageBox.Show("Finished", "Completed"); } catch { MessageBox.Show("Review your settings or plugin already exists"); } }
private void getVmMor(String vmName) { _virtualMachine = cb.getServiceUtil().GetDecendentMoRef(null, "VirtualMachine", vmName); }
private void reConfig() { String deviceType = cb.get_option("device"); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); if (deviceType.Equals("memory")) { Console.WriteLine("Reconfiguring The Virtual Machine For Memory Update " + cb.get_option("vmname")); try { vmConfigSpec.memoryAllocation = getShares(); } catch (Exception nfe) { Console.WriteLine("Value of Memory update must " + "be either Custom or Integer"); return; } } else if (deviceType.Equals("cpu")) { Console.WriteLine("Reconfiguring The Virtual Machine For CPU Update " + cb.get_option("vmname")); try { vmConfigSpec.cpuAllocation = getShares(); } catch (Exception nfe) { Console.WriteLine("Value of CPU update must " + "be either Custom or Integer"); return; } } else if (deviceType.Equals("disk")) { Console.WriteLine("Reconfiguring The Virtual Machine For Disk Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec vdiskSpec = getDiskDeviceConfigSpec(); if (vdiskSpec != null) { VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); int ckey = -1; VirtualDevice[] test = vmConfigInfo.hardware.device; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( "SCSI Controller 0")) { ckey = test[k].key; } } if (ckey == -1) { int diskCtlrKey = 1; VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec(); scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add; scsiCtrlSpec.operationSpecified = true; VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController(); scsiCtrl.busNumber = 0; scsiCtrlSpec.device = scsiCtrl; scsiCtrl.key = diskCtlrKey; scsiCtrl.sharedBus = VirtualSCSISharing.physicalSharing; String ctlrType = scsiCtrl.GetType().Name; vdiskSpec.device.controllerKey = scsiCtrl.key; VirtualDeviceConfigSpec[] vdiskSpecArray = { scsiCtrlSpec, vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } else { vdiskSpec.device.controllerKey = ckey; VirtualDeviceConfigSpec[] vdiskSpecArray = { vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } } else { return; } } else if (deviceType.Equals("nic")) { Console.WriteLine("Reconfiguring The Virtual Machine For NIC Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec nicSpec = getNICDeviceConfigSpec(); if (nicSpec != null) { VirtualDeviceConfigSpec [] nicSpecArray = { nicSpec }; vmConfigSpec.deviceChange = nicSpecArray; } else { return; } } else if (deviceType.Equals("cd")) { Console.WriteLine("Reconfiguring The Virtual Machine For CD Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec cdSpec = getCDDeviceConfigSpec(); if (cdSpec != null) { VirtualDeviceConfigSpec [] cdSpecArray = { cdSpec }; vmConfigSpec.deviceChange = cdSpecArray; } else { return; } } else { Console.WriteLine("Invlaid device type [memory|cpu|disk|nic|cd]"); return; } ManagedObjectReference tmor = cb.getConnection()._service.ReconfigVM_Task( _virtualMachine, vmConfigSpec); monitorTask(tmor); }
/// <summary> /// Get MOR of Datacenter /// </summary> /// <param name="dsMor">ManagedObjectReference</param> /// <returns>ManagedObjectReference</returns> private ManagedObjectReference getDatacenterOfDatastore(ManagedObjectReference dsMor) { ManagedObjectReference datacenter = null; // Create Property Spec PropertySpec propertySpec = new PropertySpec(); propertySpec.all = false; propertySpec.type = "Datacenter"; propertySpec.pathSet = new string[] { "name" }; // Now create Object Spec ObjectSpec objectSpec = new ObjectSpec(); objectSpec.obj = dsMor; objectSpec.skip = true; objectSpec.selectSet = buildTraversalSpecForDatastoreToDatacenter(); // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpec(); propertyFilterSpec.propSet = new PropertySpec[] { propertySpec }; propertyFilterSpec.objectSet = new ObjectSpec[] { objectSpec }; PropertyFilterSpec[] propertyFilterSpecs = new PropertyFilterSpec[] { propertyFilterSpec }; ObjectContent[] oCont = cb._svcUtil.retrievePropertiesEx(cb._connection._sic.propertyCollector, propertyFilterSpecs); if (oCont != null) { foreach (ObjectContent oc in oCont) { datacenter = oc.obj; break; } } return datacenter; }
protected void Page_Load(object sender, EventArgs e) { AuthenticateUser(); if (Request.Cookies["profileid"] != null && Request.Cookies["profileid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["profileid"].Value); } if (Request.QueryString["applicationid"] != null && Request.QueryString["applicationid"] != "") { intApplication = Int32.Parse(Request.QueryString["applicationid"]); } if (Request.Cookies["application"] != null && Request.Cookies["application"].Value != "") { intApplication = Int32.Parse(Request.Cookies["application"].Value); } oDataPoint = new DataPoint(intProfile, dsn); oUser = new Users(intProfile, dsn); oServer = new Servers(intProfile, dsn); oAsset = new Asset(intProfile, dsnAsset); oWorkstation = new Workstations(intProfile, dsn); oForecast = new Forecast(intProfile, dsn); oPlatform = new Platforms(intProfile, dsn); oType = new Types(intProfile, dsn); oModel = new Models(intProfile, dsn); oModelsProperties = new ModelsProperties(intProfile, dsn); oIPAddresses = new IPAddresses(intProfile, dsnIP, dsn); oFunction = new Functions(intProfile, dsn, intEnvironment); oOperatingSystem = new OperatingSystems(intProfile, dsn); oServicePack = new ServicePacks(intProfile, dsn); oClass = new Classes(intProfile, dsn); oEnvironment = new Environments(intProfile, dsn); oDomain = new Domains(intProfile, dsn); oVirtualHDD = new VirtualHDD(intProfile, dsn); oVirtualRam = new VirtualRam(intProfile, dsn); oZeus = new Zeus(intProfile, dsnZeus); oLog = new Log(intProfile, dsn); oService = new Services(intProfile, dsn); oServiceRequest = new ServiceRequests(intProfile, dsn); oResourceRequest = new ResourceRequest(intProfile, dsn); if (oUser.IsAdmin(intProfile) == true || (oDataPoint.GetPagePermission(intApplication, "ASSET") == true || intDataPointAvailableAsset == 1)) { panAllow.Visible = true; if (Request.QueryString["save"] != null) { panSave.Visible = true; } if (Request.QueryString["error"] != null) { panError.Visible = true; // -100: More than one device name // -10: No device names // -5: Improper Name Format // -1: ServerID = 0 if (Request.QueryString["error"] == "-100") { lblError.Text = "More than one name"; } else if (Request.QueryString["error"] == "-10") { lblError.Text = "User Cancelled Prompt"; } else if (Request.QueryString["error"] == "-5") { lblError.Text = "Name is in Incorrect Format"; } else if (Request.QueryString["error"] == "-1") { lblError.Text = "DeviceID = 0"; } else { lblError.Text = "Generic Error"; } } Int32.TryParse(oFunction.decryptQueryString(Request.QueryString["id"]), out intID); if (Request.QueryString["close"] != null) { Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "close", "<script type=\"text/javascript\">window.close();<" + "/" + "script>"); } else if (intID > 0) { DataSet ds = oDataPoint.GetAsset(intID); if (ds.Tables[0].Rows.Count == 1) { // Load General Information intAsset = Int32.Parse(ds.Tables[0].Rows[0]["id"].ToString()); lblAssetID.Text = "#" + intAsset.ToString(); string strSerial = ds.Tables[0].Rows[0]["serial"].ToString(); string strAsset = ds.Tables[0].Rows[0]["asset"].ToString(); string strHeader = (strSerial.Length > 15 ? strSerial.Substring(0, 15) + "..." : strSerial); lblHeader.Text = """ + strHeader.ToUpper() + """; Master.Page.Title = "DataPoint | VMware Workstation (" + strHeader + ")"; lblHeaderSub.Text = "Provides all the information about a VMware Workstation..."; int intMenuTab = 0; if (Request.QueryString["menu_tab"] != null && Request.QueryString["menu_tab"] != "") { intMenuTab = Int32.Parse(Request.QueryString["menu_tab"]); } Tab oTab = new Tab(hdnTab.ClientID, intMenuTab, "divMenu1", true, false); oTab.AddTab("Asset Information", ""); oTab.AddTab("Guest Information", ""); oTab.AddTab("Account Information", ""); oTab.AddTab("Resource Dependencies", ""); oTab.AddTab("Provisioning Information", ""); if (oUser.IsAdmin(intProfile) == true || oDataPoint.GetFieldPermission(intProfile, "SERVER_ADMIN") == true) { oTab.AddTab("Administration", ""); panAdministration.Visible = true; } strMenuTab1 = oTab.GetTabs(); if (!IsPostBack) { // Asset Information oDataPoint.LoadTextBox(txtPlatformSerial, intProfile, null, "", lblPlatformSerial, fldPlatformSerial, "WORKSTATION_VMWARE_SERIAL", strSerial, "", false, true); oDataPoint.LoadTextBox(txtPlatformAsset, intProfile, null, "", lblPlatformAsset, fldPlatformAsset, "WORKSTATION_VMWARE_ASSET", strAsset, "", false, true); int intAssetAttribute = Int32.Parse(oAsset.Get(intAsset, "asset_attribute")); oDataPoint.LoadDropDown(ddlAssetAttribute, intProfile, null, "", lblAssetAttribute, fldAssetAttribute, "ASSET_ATTRIBUTE", "Name", "AttributeId", oAsset.getAssetAttributes(null, "", 1), intAssetAttribute, true, false, false); oDataPoint.LoadTextBox(txtAssetAttributeComment, intProfile, null, "", lblAssetAttributeComment, fldAssetAttributeComment, "ASSET_ATTRIBUTE_COMMENT", oAsset.getAssetAttributesComments(intAsset), "", false, true); ddlAssetAttribute.Attributes.Add("onclick", "return SetControlsForAssetAttributes()"); ddlPlatform.Attributes.Add("onchange", "PopulatePlatformTypes('" + ddlPlatform.ClientID + "','" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformType.Attributes.Add("onchange", "PopulatePlatformModels('" + ddlPlatformType.ClientID + "','" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModel.Attributes.Add("onchange", "PopulatePlatformModelProperties('" + ddlPlatformModel.ClientID + "','" + ddlPlatformModelProperty.ClientID + "');ResetDropDownHidden('" + hdnModel.ClientID + "');"); ddlPlatformModelProperty.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformModelProperty.ClientID + "','" + hdnModel.ClientID + "');"); int intModel = Int32.Parse(oAsset.Get(intAsset, "modelid")); hdnModel.Value = intModel.ToString(); int intModelParent = Int32.Parse(oModelsProperties.Get(intModel, "modelid")); int intType = oModel.GetType(intModelParent); string strExecute = oType.Get(intType, "forecast_execution_path"); if (strExecute != "") { DataSet dsVirtual = oWorkstation.GetVirtualAsset(intAsset); if (dsVirtual.Tables[0].Rows.Count > 0) { btnExecute.Attributes.Add("onclick", "return OpenWindow('FORECAST_EXECUTE','" + strExecute + "?id=" + dsVirtual.Tables[0].Rows[0]["answerid"].ToString() + "');"); } else { btnExecute.Enabled = false; } } else { btnExecute.Enabled = false; } int intPlatform = oType.GetPlatform(intType); oDataPoint.LoadDropDown(ddlPlatform, intProfile, null, "", lblPlatform, fldPlatform, "WORKSTATION_VMWARE_PLATFORM", "name", "platformid", oPlatform.Gets(1), intPlatform, false, false, true); oDataPoint.LoadDropDown(ddlPlatformType, intProfile, null, "", lblPlatformType, fldPlatformType, "WORKSTATION_VMWARE_TYPE", "name", "id", oType.Gets(intPlatform, 1), intType, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModel, intProfile, null, "", lblPlatformModel, fldPlatformModel, "WORKSTATION_VMWARE_MODEL", "name", "id", oModel.Gets(intType, 1), intModelParent, false, false, true); oDataPoint.LoadDropDown(ddlPlatformModelProperty, intProfile, null, "", lblPlatformModelProperty, fldPlatformModelProperty, "WORKSTATION_VMWARE_MODEL_PROP", "name", "id", oModelsProperties.GetModels(0, intModelParent, 1), intModel, false, false, true); // Get Asset int intWorkstation = 0; DataSet dsAsset = oWorkstation.GetVirtualAsset(intAsset); if (dsAsset.Tables[0].Rows.Count > 0) { intWorkstation = Int32.Parse(dsAsset.Tables[0].Rows[0]["id"].ToString()); lblWorkstation.Text = intWorkstation.ToString(); txtStep.Text = dsAsset.Tables[0].Rows[0]["step"].ToString(); oDataPoint.LoadTextBoxDeviceName(txtName, btnName, null, true, hdnPNC, intProfile, null, "", lblName, fldName, "WORKSTATION_VMWARE_NAME", dsAsset.Tables[0].Rows[0]["name"].ToString(), "", false, false); if (txtName.Text != "") { lblHeader.Text += " [" + txtName.Text + "]"; } lblStatus.Text = dsAsset.Tables[0].Rows[0]["statusname"].ToString(); // Administrative Functions if (Request.QueryString["admin"] != null) { if (Request.QueryString["result"] != null) { strAdministration = "<tr><td>" + oFunction.decryptQueryString(Request.QueryString["result"]) + "</td></tr>"; } if (Request.QueryString["output"] != null) { DataSet dsOutput = oWorkstation.GetVirtualOutput(intWorkstation); foreach (DataRow drOutput in dsOutput.Tables[0].Rows) { strAdministration += "<tr><td><a href=\"javascript:void(0);\" onclick=\"ShowHideDiv2('div" + drOutput["id"].ToString() + "');\">" + drOutput["type"].ToString() + "</a></td></tr>"; strAdministration += "<tr id=\"div" + drOutput["id"].ToString() + "\" style=\"display:none\"><td>" + oFunction.FormatText(drOutput["output"].ToString()) + "</td></tr>"; } if (lblStatus.Text != "") { strAdministration += "<tr><td>" + oLog.GetEvents(oLog.GetEventsByName(txtName.Text.ToUpper(), (int)LoggingType.Error), intEnvironment) + "</td></tr>"; } } } int intClass = Int32.Parse(dsAsset.Tables[0].Rows[0]["classid"].ToString()); int intEnv = Int32.Parse(dsAsset.Tables[0].Rows[0]["environmentid"].ToString()); hdnEnvironment.Value = intEnv.ToString(); oDataPoint.LoadDropDown(ddlPlatformClass, intProfile, null, "", lblPlatformClass, fldPlatformClass, "WORKSTATION_VMWARE_CLASS", "name", "id", oClass.GetWorkstationVMwares(1), intClass, false, false, true); oDataPoint.LoadDropDown(ddlPlatformEnvironment, intProfile, null, "", lblPlatformEnvironment, fldPlatformEnvironment, "WORKSTATION_VMWARE_ENVIRONMENT", "name", "id", oClass.GetEnvironment(intClass, 0), intEnv, false, false, true); ddlStatus.SelectedValue = dsAsset.Tables[0].Rows[0]["status"].ToString(); ddlStatus.Enabled = (intAssetAttribute == (int)AssetAttribute.Ok); panStatus.Visible = (ddlStatus.Enabled == false); int intOS = Int32.Parse(dsAsset.Tables[0].Rows[0]["osid"].ToString()); bool boolXP = (oOperatingSystem.Get(intOS, "code") == "XP"); bool boolWin7 = (oOperatingSystem.Get(intOS, "code") == "7"); oDataPoint.LoadDropDown(ddlPlatformOS, intProfile, null, "", lblPlatformOS, fldPlatformOS, "WORKSTATION_VMWARE_OS", "name", "id", oOperatingSystem.Gets(1, 1), intOS, false, false, true); oDataPoint.LoadDropDown(ddlPlatformServicePack, intProfile, null, "", lblPlatformServicePack, fldPlatformServicePack, "WORKSTATION_VMWARE_SP", "name", "id", oOperatingSystem.GetServicePack(intOS), Int32.Parse(dsAsset.Tables[0].Rows[0]["spid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformDomain, intProfile, null, "", lblPlatformDomain, fldPlatformDomain, "WORKSTATION_VMWARE_DOMAIN", "name", "id", oDomain.Gets(1), Int32.Parse(dsAsset.Tables[0].Rows[0]["domainid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformHDD, intProfile, null, "", lblPlatformHDD, fldPlatformHDD, "WORKSTATION_VMWARE_HDD", "name", "id", oVirtualHDD.GetVMwares((boolXP ? 1 : 0), (boolWin7 ? 1 : 0), 1), Int32.Parse(dsAsset.Tables[0].Rows[0]["hddid"].ToString()), false, false, true); oDataPoint.LoadDropDown(ddlPlatformRam, intProfile, null, "", lblPlatformRam, fldPlatformRam, "WORKSTATION_VMWARE_RAM", "name", "id", oVirtualRam.GetVMwares((boolXP ? 1 : 0), (boolWin7 ? 1 : 0), 1), Int32.Parse(dsAsset.Tables[0].Rows[0]["ramid"].ToString()), false, false, true); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } // Get Host oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(dsAsset.Tables[0].Rows[0]["hostname"].ToString()), lblHostName, fldHostName, "WORKSTATION_VMWARE_HOST", dsAsset.Tables[0].Rows[0]["hostname"].ToString(), "", false, false); if (Request.Cookies["virtual_guest"] != null && Request.Cookies["virtual_guest"].Value != "") { string strHost = ""; string strFind = txtName.Text; //strFind = "ohcleapp103d"; DateTime datStart = DateTime.Parse(Request.Cookies["virtual_guest"].Value); Response.Cookies["virtual_guest"].Value = ""; VMWare oVMWare = new VMWare(intProfile, dsn); string strConnect = oVMWare.Connect(strFind); VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); try { ManagedObjectReference oVM = oVMWare.GetVM(strFind); ManagedObjectReference oParent = (ManagedObjectReference)oVMWare.getObjectProperty(oVM, "parent"); ManagedObjectReference oDataCenter = (ManagedObjectReference)oVMWare.getObjectProperty(oParent, "parent"); string strDataCenter = (string)oVMWare.getObjectProperty(oDataCenter, "name"); GuestInfo ginfo = (GuestInfo)oVMWare.getObjectProperty(oVM, "guest"); lblGuestState.Text = ginfo.guestState; GuestNicInfo[] nInfo = ginfo.net; foreach (GuestNicInfo nic in nInfo) { string[] strIPAddresses = nic.ipAddress; foreach (string strIPAddress in strIPAddresses) { if (lblIPAddress.Text != "") { lblIPAddress.Text += ", "; } lblIPAddress.Text += strIPAddress; } if (lblMACAddress.Text != "") { lblMACAddress.Text += ", "; } lblMACAddress.Text += nic.macAddress; if (lblNetwork.Text != "") { lblNetwork.Text += ", "; } lblNetwork.Text += nic.network; } // HDD GuestDiskInfo[] oVMDisks = ginfo.disk; foreach (GuestDiskInfo oDisk in oVMDisks) { if (lblHDD.Text != "") { lblHDD.Text += "<br/>"; } double dblCapacity = double.Parse(oDisk.capacity.ToString()); dblCapacity = dblCapacity / 1024.00; dblCapacity = dblCapacity / 1024.00; dblCapacity = dblCapacity / 1024.00; double dblAvailable = double.Parse(oDisk.freeSpace.ToString()); dblAvailable = dblAvailable / 1024.00; dblAvailable = dblAvailable / 1024.00; dblAvailable = dblAvailable / 1024.00; lblHDD.Text += oDisk.diskPath + " " + dblCapacity.ToString("F") + " GB (" + dblAvailable.ToString("F") + " GB available)"; } // Status VirtualMachineSummary oVMSummary = (VirtualMachineSummary)oVMWare.getObjectProperty(oVM, "summary"); ManagedEntityStatus oVMStatus = oVMSummary.overallStatus; //lblOverallStatus.Text = (string)oVMStatus; lblOverallStatus.Text = Enum.GetName(typeof(ManagedEntityStatus), (ManagedEntityStatus)oVMStatus); // RAM & CPUs & Host VirtualMachineConfigSummary oVMConfig = oVMSummary.config; lblRAM.Text = oVMConfig.memorySizeMB.ToString(); lblCPUs.Text = oVMConfig.numCpu.ToString(); VirtualMachineRuntimeInfo oVMRuntime = oVMSummary.runtime; ManagedObjectReference oVMHost = oVMRuntime.host; strHost = (string)oVMWare.getObjectProperty(oVMHost, "name"); if (strHost.IndexOf(".") > -1) { strHost = strHost.Substring(0, strHost.IndexOf(".")); } lblVirtualCenter.Text = oVMWare.VirtualCenter(); lblDataCenter.Text = oVMWare.DataCenter(); } catch { } finally { if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } } if (strHost != "") { panGuestYes.Visible = true; oDataPoint.LoadTextBox(txtHostName, intProfile, btnHostName, "/datapoint/asset/server.aspx?t=name&q=" + oFunction.encryptQueryString(strHost), lblHostName, fldHostName, "WORKSTATION_VMWARE_HOST", strHost, "", false, false); } else { panGuestNo.Visible = true; } TimeSpan oSpan = DateTime.Now.Subtract(datStart); btnGuestQuery.Enabled = false; btnGuestQuery.Text = "Query Time: " + oSpan.TotalSeconds.ToString("0") + " seconds..."; } oDataPoint.LoadPanel(panGuestQuery, intProfile, fldHostQuery, "WORKSTATION_VMWARE_HOST_QUERY"); // Account Information DataSet dsAccounts = oWorkstation.GetAccountsVMware(intWorkstation); rptAccounts.DataSource = dsAccounts; rptAccounts.DataBind(); lblNone.Visible = (rptAccounts.Items.Count == 0); // Resource Dependencies rptServiceRequests.DataSource = ds.Tables[1]; rptServiceRequests.DataBind(); trServiceRequests.Visible = (rptServiceRequests.Items.Count == 0); foreach (RepeaterItem ri in rptServiceRequests.Items) { Label lblRequestID = (Label)ri.FindControl("lblRequestID"); Label lblServiceID = (Label)ri.FindControl("lblServiceID"); Label lblNumber = (Label)ri.FindControl("lblNumber"); int intService = Int32.Parse(lblServiceID.Text); Label lblDetails = (Label)ri.FindControl("lblDetails"); Label lblProgress = (Label)ri.FindControl("lblProgress"); if (lblProgress.Text == "") { lblProgress.Text = "<i>Unavailable</i>"; } else { int intResource = Int32.Parse(lblProgress.Text); //lblProgress.Text = oResourceRequest.GetStatus(Int32.Parse(lblRequestID.Text), Int32.Parse(lblServiceID.Text), Int32.Parse(lblNumber.Text), true, true, dsnServiceEditor, dsnAsset, intServiceDecommission); lblProgress.Text = oResourceRequest.GetStatus(null, null, Int32.Parse(lblRequestID.Text), Int32.Parse(lblServiceID.Text), null, Int32.Parse(lblNumber.Text), true, dsnServiceEditor)[0].status; /* * double dblAllocated = 0.00; * double dblUsed = 0.00; * int intStatus = 0; * bool boolAssigned = false; * DataSet dsResource = oDataPoint.GetServiceRequestResource(intResource); * if (dsResource.Tables[0].Rows.Count > 0) * Int32.TryParse(dsResource.Tables[0].Rows[0]["status"].ToString(), out intStatus); * foreach (DataRow drResource in dsResource.Tables[1].Rows) * { * boolAssigned = true; * dblAllocated += double.Parse(drResource["allocated"].ToString()); * dblUsed += double.Parse(drResource["used"].ToString()); * intStatus = Int32.Parse(drResource["status"].ToString()); * } * if (intStatus == (int)ResourceRequestStatus.Closed) * lblProgress.Text = oServiceRequest.GetStatusBar(100.00, "100", "12", true); * else if (intStatus == (int)ResourceRequestStatus.Cancelled) * lblProgress.Text = "Cancelled"; * else if (boolAssigned == false) * { * string strManager = ""; * DataSet dsManager = oService.GetUser(intService, 1); // Managers * foreach (DataRow drManager in dsManager.Tables[0].Rows) * { * if (strManager != "") * strManager += "\\n"; * int intManager = Int32.Parse(drManager["userid"].ToString()); * strManager += " - " + oUser.GetFullName(intManager) + " [" + oUser.GetName(intManager) + "]"; * } * lblProgress.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"alert('This request is pending assignment by the following...\\n\\n" + strManager + "');\">Pending Assignment</a>"; * } * else if (dblAllocated > 0.00) * lblProgress.Text = oServiceRequest.GetStatusBar((dblUsed / dblAllocated) * 100.00, "100", "12", true); * else * lblProgress.Text = "<i>N / A</i>"; */ lblDetails.Text = "<a href=\"javascript:void(0);\" class=\"lookup\" onclick=\"OpenNewWindowMenu('/datapoint/service/resource.aspx?id=" + oFunction.encryptQueryString(intResource.ToString()) + "', '800', '600');\">" + lblDetails.Text + "</a>"; } } // Provioning History rptHistory.DataSource = SqlHelper.ExecuteDataset(dsnAsset, CommandType.Text, oDataPoint.AssetHistorySelect(intAsset)); rptHistory.DataBind(); lblHistory.Visible = (rptHistory.Items.Count == 0); oDataPoint.LoadPanel(panProvisioning, intProfile, fldProvisioning, "WORKSTATION_VMWARE_STATUS"); } } else { if (Request.QueryString["t"] != null && Request.QueryString["q"] != null) { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&r=0"); } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } } } else if (Request.QueryString["q"] != null && Request.QueryString["q"] != "") { string strQuery = oFunction.decryptQueryString(Request.QueryString["q"]); DataSet ds = oDataPoint.GetAssetName(strQuery, intID, 0, "", "", 0); if (ds.Tables[0].Rows.Count == 1) { intAsset = Int32.Parse(ds.Tables[0].Rows[0]["assetid"].ToString()); Response.Redirect(Request.Path + "?t=" + Request.QueryString["t"] + "&q=" + Request.QueryString["q"] + "&id=" + oFunction.encryptQueryString(intAsset.ToString())); } } else { Response.Redirect("/datapoint/asset/datapoint_asset_search.aspx"); } btnClose.Attributes.Add("onclick", "window.close();return false;"); btnPrint.Attributes.Add("onclick", "window.print();return false;"); btnName.Attributes.Add("onclick", "return OpenWindow('DEVICE_NAME','?assetid=" + intAsset.ToString() + "');"); btnSave.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); btnSaveClose.Attributes.Add("onclick", oDataPoint.LoadValidation("ProcessControlButton()")); ddlPlatformClass.Attributes.Add("onchange", "PopulateEnvironments('" + ddlPlatformClass.ClientID + "','" + ddlPlatformEnvironment.ClientID + "',0);"); ddlPlatformEnvironment.Attributes.Add("onchange", "UpdateDropDownHidden('" + ddlPlatformEnvironment.ClientID + "','" + hdnEnvironment.ClientID + "');"); btnGuestQuery.Attributes.Add("onclick", "ProcessButton(this,'Querying... please be patient...','225') && ProcessControlButton();"); btnOutput.Attributes.Add("onclick", "return ProcessButton(this) && ProcessControlButton();"); } else { panDenied.Visible = true; } }
/// <summary> /// Gets datacenter for particular vm managed object reference. /// </summary> /// <param name="vmmor"></param> /// <returns>Returns string value dcName.</returns> private String getDataCenter(ManagedObjectReference vmmor) { ManagedObjectReference morParent = cb.getServiceUtil().GetMoRefProp(vmmor,"parent"); morParent = cb.getServiceUtil().GetMoRefProp(morParent, "parent"); Object objdcName = cb.getServiceUtil().GetDynamicProperty(morParent, "name"); String dcName = objdcName.ToString(); return dcName; }
private void doRemoveVirtualNic() { ManagedObjectReference dcmor; ManagedObjectReference hostfoldermor; ManagedObjectReference hostmor = null; datacenter = cb.get_option("datacenter"); host = cb.get_option("host"); portGroupName = cb.get_option("portgroupname"); try { if (((datacenter != null) && (host != null)) || ((datacenter != null) && (host == null))) { dcmor = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", datacenter); if (dcmor == null) { Console.WriteLine("Datacenter not found"); return; } hostfoldermor = vmUtils.getHostFolder(dcmor); hostmor = vmUtils.getHost(hostfoldermor, host); } else if ((datacenter == null) && (host != null)) { hostmor = vmUtils.getHost(null, host); } if (hostmor != null) { Object cmobj = cb.getServiceUtil().GetDynamicProperty(hostmor, "configManager"); HostConfigManager configMgr = (HostConfigManager)cmobj; ManagedObjectReference nwSystem = configMgr.networkSystem; Object obj = cb.getServiceUtil().GetDynamicProperty(nwSystem, "networkInfo.vnic"); HostVirtualNic[] hvns = (HostVirtualNic[])obj; Boolean found_one = false; if (hvns != null) { for (int i = 0; i < hvns.Length; i++) { HostVirtualNic nic = hvns[i]; String portGroup = nic.portgroup; if (portGroup.Equals(portGroupName)) { found_one = true; cb.getConnection()._service.RemoveVirtualNic(nwSystem, nic.device); } } } if (found_one) { Console.WriteLine(cb.getAppName() + " : Successful removing : " + portGroupName); } else { Console.WriteLine(cb.getAppName() + " : PortGroupName not found failed removing : " + portGroupName); } } else { Console.WriteLine("Host not found"); } } catch (SoapException e) { if (e.Detail.FirstChild.LocalName.Equals("NotFoundFault")) { Console.WriteLine(cb.getAppName() + " : Failed : virtual network adapter cannot be found. "); } else if (e.Detail.FirstChild.LocalName.Equals("HostConfigFault")) { Console.WriteLine(cb.getAppName() + " : Failed : Configuration falilures. "); } } catch (Exception e) { Console.WriteLine(cb.getAppName() + " : Failed removing nic: " + portGroupName); throw e; } }