protected override async Task ExecuteAsync(CancellationToken cancellationToken) { await Task.Yield(); while (!cancellationToken.IsCancellationRequested) { try { _options = _optionsMonitor.CurrentValue; _client = _connectionService.GetClient(); _sic = _connectionService.GetServiceContent(); _props = _connectionService.GetProps(); _tasksPending = false; using (var scope = _serviceProvider.CreateScope()) { _dbContext = scope.ServiceProvider.GetRequiredService <VmContext>(); await processTasks(); } } catch (Exception ex) { _logger.LogError(ex, "Exception in TaskService"); } var intervalMilliseconds = _tasksPending ? _options.ReCheckTaskProgressIntervalMilliseconds : _options.CheckTaskProgressIntervalMilliseconds; _taskServiceHealthCheck.CompletedRun(); await _resetEvent.WaitAsync(new TimeSpan(0, 0, 0, 0, intervalMilliseconds)); } }
public static SmsProvider[] QueryProvider(string server, string userName, string password) { SmsProvider[] providers; var binding = new BasicHttpsBinding { AllowCookies = true }; var vimEndpoint = new EndpointAddress(string.Format("https://{0}/sdk/vimService", server)); var smsEndpoint = new EndpointAddress(string.Format("https://{0}/sms/sdk", server)); ServicePointManager.ServerCertificateValidationCallback += (sender, x509Certificate, chain, errors) => true; using (var client = new VimPortTypeClient(binding, vimEndpoint)) { client.Open(); var vimProxy = new VimProxy(client); string sessionId; var content = vimProxy.RetrieveServiceContent(); var credential = new NetworkCredential { UserName = userName, Password = password }; vimProxy.Login(content.sessionManager, credential, null, out sessionId); using (var smsClient = new SmsPortTypeClient(binding, smsEndpoint)) { smsClient.Open(); var smsProxy = new SmsProxy(smsClient, sessionId); var storageManager = smsProxy.QueryStorageManager(); var providerRefs = smsProxy.QueryProvider(storageManager); providers = providerRefs.Select(smsProxy.QueryProviderInfo).Select(GetProvider).ToArray(); smsClient.Close(); } vimProxy.Logout(content.sessionManager); client.Close(); } return(providers); }
public VimGuestOperation( VimPortTypeClient vimService, ManagedObjectReference morPropCollector, ManagedObjectReference morGuestOperationsManager, ManagedObjectReference morVM, string user, string pwd ) { _vimService = vimService; _morPropCollector = morPropCollector; _morGuestOperationsManager = morGuestOperationsManager; _morVM = morVM; //_user = user; //_password = password; _NamePasswordAuthentication = new NamePasswordAuthentication() { interactiveSession = false, username = user, password = pwd }; VimPropCollector pc = new VimPropCollector(_vimService, _morPropCollector); _morFileManager = (ManagedObjectReference)pc.Get(morGuestOperationsManager, "fileManager"); _morProcessManager = (ManagedObjectReference)pc.Get(morGuestOperationsManager, "processManager"); }
private async Task Connect() { _lastAction = DateTime.UtcNow; await Task.Delay(0); if (_vim != null && _vim.State == CommunicationState.Opened) { return; } //only want one client object created, so first one through wins //everyone else wait here lock (_config) { if (_vim != null && _vim.State == CommunicationState.Faulted) { _logger.LogDebug($"{_config.Url} CommunicationState is Faulted."); Disconnect().Wait(); } if (_vim == null) { try { DateTime sp = DateTime.Now; _logger.LogDebug($"Instantiating client {_config.Host}..."); VimPortTypeClient client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, _config.Url); _logger.LogDebug($"client: [{client}]"); _logger.LogDebug($"Instantiated {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogInformation($"Connecting to {_config.Url}..."); _sic = client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }).Result; _config.IsVCenter = _sic.about.apiType == "VirtualCenter"; _props = _sic.propertyCollector; _vdm = _sic.virtualDiskManager; _file = _sic.fileManager; _logger.LogDebug($"Connected {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogInformation($"logging into {_config.Host}...[{_config.User}]"); _session = client.LoginAsync(_sic.sessionManager, _config.User, _config.Password, null).Result; _logger.LogDebug($"Authenticated {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); sp = DateTime.Now; _logger.LogDebug($"Initializing {_config.Host}..."); InitReferences(client).Wait(); _logger.LogDebug($"Initialized {_config.Host} in {DateTime.Now.Subtract(sp).TotalSeconds} seconds"); _vim = client; } catch (Exception ex) { _logger.LogError(0, ex, $"Failed to connect with " + _config.Url); } } } }
private async Task <ServiceContent> ConnectToHost(VimPortTypeClient client) { _logger.LogInformation($"Connect(): Connecting to {_options.Host}..."); var sic = await client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }); return(sic); }
public CListVMs(VimPortTypeClient vimService, ManagedObjectReference morPropCollector) { _vimService = vimService; _morPropCollector = morPropCollector; _pc = new VimPropCollector(_vimService, morPropCollector); _sb = new StringBuilder(); _sw = new StringWriter(_sb); }
private async Task <UserSession> ConnectToSession(VimPortTypeClient client, ServiceContent sic) { _logger.LogInformation($"Connect(): logging into {_options.Host}...[{_options.Username}]"); var session = await client.LoginAsync(sic.sessionManager, _options.Username, _options.Password, null); _logger.LogInformation($"Connect(): Session created."); return(session); }
public void Disconnect() { _logger.LogInformation($"Disconnect()"); _client.Dispose(); _client = null; _sic = null; _session = null; }
public MyVMOperation( VimPortTypeClient vimService, ManagedObjectReference morPropCollector, ManagedObjectReference morThis) { _vimService = vimService; _pc = new VimPropCollector(_vimService, morPropCollector); _morThis = morThis; }
public MyVMTask( VimPortTypeClient vimService, VimPropCollector PropCollector, ManagedObjectReference morThis) { _vimService = vimService; _pc = PropCollector; _morThis = morThis; }
private async Task <NetVimClient.ObjectContent[]> LoadReferenceTree(VimPortTypeClient client) { var plan = new TraversalSpec { name = "FolderTraverseSpec", type = "Folder", path = "childEntity", selectSet = new SelectionSpec[] { new TraversalSpec() { type = "Datacenter", path = "datastore", selectSet = new SelectionSpec[] { new SelectionSpec { name = "FolderTraverseSpec" } } }, new TraversalSpec() { type = "Folder", path = "childEntity", selectSet = new SelectionSpec[] { new SelectionSpec { name = "FolderTraverseSpec" } } } } }; var props = new PropertySpec[] { new PropertySpec { type = "Datastore", pathSet = new string[] { "name", "browser" } } }; ObjectSpec objectspec = new ObjectSpec(); objectspec.obj = _sic.rootFolder; objectspec.selectSet = new SelectionSpec[] { plan }; PropertyFilterSpec filter = new PropertyFilterSpec(); filter.propSet = props; filter.objectSet = new ObjectSpec[] { objectspec }; PropertyFilterSpec[] filters = new PropertyFilterSpec[] { filter }; RetrievePropertiesResponse response = await client.RetrievePropertiesAsync(_props, filters); return(response.returnval); }
public async Task Disconnect() { _logger.LogDebug($"Disconnecting from {this.Name}"); await Task.Delay(500); _vim.Dispose(); _vim = null; _sic = null; _session = null; }
private async void Run() { while (true) { _client = _connectionService.GetClient(); _sic = _connectionService.GetServiceContent(); _props = _connectionService.GetProps(); await processTasks(); await Task.Delay(new TimeSpan(0, 0, 0, 0, _options.CheckTaskProgressIntervalMilliseconds)); } }
public VmService( IOptions <VmOptions> options, IOptions <RewriteHostOptions> rewriteHostOptions, ILogger <VmService> logger, IConfiguration configuration, IConnectionService connectionService ) { _options = options.Value; _rewriteHostOptions = rewriteHostOptions.Value; _logger = logger; vmApiClient.BaseAddress = new Uri(_options.ApiUrl); vmApiClient.DefaultRequestHeaders.Accept.Clear(); vmApiClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); _connectionService = connectionService; _client = connectionService.GetClient(); _sic = connectionService.GetServiceContent(); _props = connectionService.GetProps(); _configuration = configuration; }
public static SmsProvider RegisterProvider( ProviderElement providerConfiguration, X509Certificate2 vasaCertificate, String vCenter, String vCenterUserName, String vCenterPassword) { SmsProvider provider; var smsData = new VasaProviderSpec { name = providerConfiguration.Name, url = String.Format("{0}", providerConfiguration.VasaVersionXmlUri), username = providerConfiguration.Credentials.Login, password = providerConfiguration.Credentials.Password, certificate = Convert.ToBase64String(vasaCertificate.RawData) }; var binding = new BasicHttpsBinding { AllowCookies = true }; var vimEndpoint = new EndpointAddress(string.Format("https://{0}/sdk/vimService", vCenter)); var smsEndpoint = new EndpointAddress(string.Format("https://{0}/sms/sdk", vCenter)); ServicePointManager.ServerCertificateValidationCallback += (sender, x509Certificate, chain, errors) => true; using (var client = new VimPortTypeClient(binding, vimEndpoint)) { client.Open(); var vimProxy = new VimProxy(client); string sessionId; var content = vimProxy.RetrieveServiceContent(); var vCenterCredential = new NetworkCredential { UserName = vCenterUserName, Password = vCenterPassword }; vimProxy.Login(content.sessionManager, vCenterCredential, null, out sessionId); using (var smsClient = new SmsPortTypeClient(binding, smsEndpoint)) { smsClient.Open(); var smsProxy = new SmsProxy(smsClient, sessionId); var storageManager = smsProxy.QueryStorageManager(); var taskRef = smsProxy.RegisterProvider(storageManager, smsData); var timeout = TimeSpan.FromMinutes(10); if (!smsProxy.WaitSmsTask(taskRef, timeout)) { try { var vimTaskRef = new DataCore.Vim.ManagedObjectReference { type = taskRef.type, Value = taskRef.Value }; client.CancelTask(vimTaskRef); } catch (Exception ex) { _traceSource.TraceEvent(TraceEventType.Warning, 0, Resources.ErrorCancelingVasaProviderRegistration, taskRef.Value, ex.ToString()); } var msg = String.Format( Resources.VasaProviderRegistrationTimeoutError, taskRef.Value, timeout); _traceSource.TraceEvent(TraceEventType.Error, 0, msg); throw new TimeoutException(msg); } var task = smsProxy.QuerySmsTaskInfo(taskRef); if (task.state.Equals("error", StringComparison.OrdinalIgnoreCase)) { var error = task.error; var msg = String.Format( Resources.ErrorOnVasaProviderRegistration, error.fault.GetType().Name, error.localizedMessage); _traceSource.TraceEvent(TraceEventType.Error, 0, msg); throw new Exception(msg); } var result = smsProxy.QuerySmsTaskResult(taskRef); var providerInfo = smsProxy.QueryProviderInfo((Sms.ManagedObjectReference)result); provider = GetProvider(providerInfo); smsClient.Close(); } vimProxy.Logout(content.sessionManager); client.Close(); } return(provider); }
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, takes a few minutes..."); binding = new System.ServiceModel.BasicHttpsBinding { AllowCookies = true }; binding.Security.Mode = System.ServiceModel.BasicHttpsSecurityMode.Transport; 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) { //Login with username and password userSession = vim.Login(serviceContent.sessionManager, username, password, null); } /*else * { * //Login with SSPI * byte[] rawToken = GetSSPIToken(PackageNames.Kerberos); * string token = Convert.ToBase64String(rawToken); * var token2 = System.Text.Encoding.Default.GetString(rawToken); * try * { * vim.LoginBySSPI(serviceContent.sessionManager, token, null); * } * catch (Exception exception) * { * Console.Out.WriteLine(exception.ToString()); * } * * }*/ 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); } } catch (Exception fault) //Generic catch all { Error(fault); } }
private async Task <ObjectContent[]> LoadReferenceTree(VimPortTypeClient client) { var plan = new TraversalSpec { name = "FolderTraverseSpec", type = "Folder", path = "childEntity", selectSet = new SelectionSpec[] { new TraversalSpec() { type = "Datacenter", path = "hostFolder", selectSet = new SelectionSpec[] { new SelectionSpec { name = "FolderTraverseSpec" } } }, new TraversalSpec() { type = "Datacenter", path = "networkFolder", selectSet = new SelectionSpec[] { new SelectionSpec { name = "FolderTraverseSpec" } } }, new TraversalSpec() { type = "ComputeResource", path = "resourcePool", selectSet = new SelectionSpec[] { new TraversalSpec { type = "ResourcePool", path = "resourcePool" } } }, new TraversalSpec() { type = "ComputeResource", path = "host" }, new TraversalSpec() { type = "Folder", path = "childEntity" } } }; var props = new PropertySpec[] { new PropertySpec { type = "Datacenter", pathSet = new string[] { "name", "parent", "vmFolder" } }, new PropertySpec { type = "ComputeResource", pathSet = new string[] { "name", "parent", "resourcePool", "host" } }, new PropertySpec { type = "HostSystem", pathSet = new string[] { "configManager" } }, new PropertySpec { type = "ResourcePool", pathSet = new string[] { "name", "parent", "resourcePool" } }, new PropertySpec { type = "DistributedVirtualSwitch", pathSet = new string[] { "name", "parent", "uuid" } }, new PropertySpec { type = "DistributedVirtualPortgroup", pathSet = new string[] { "name", "parent", "config" } } }; ObjectSpec objectspec = new ObjectSpec(); objectspec.obj = _sic.rootFolder; objectspec.selectSet = new SelectionSpec[] { plan }; PropertyFilterSpec filter = new PropertyFilterSpec(); filter.propSet = props; filter.objectSet = new ObjectSpec[] { objectspec }; PropertyFilterSpec[] filters = new PropertyFilterSpec[] { filter }; RetrievePropertiesResponse response = await client.RetrievePropertiesAsync(_props, filters); return(response.returnval); }
private async Task InitReferences(VimPortTypeClient client) { var clunkyTree = await LoadReferenceTree(client); if (clunkyTree.Length == 0) { throw new InvalidOperationException(); } string[] path = _config.PoolPath.ToLower().Split(new char[] { '/', '\\' }); string datacenter = (path.Length > 0) ? path[0] : ""; string cluster = (path.Length > 1) ? path[1] : ""; string pool = (path.Length > 2) ? path[2] : ""; var dcContent = (clunkyTree.FindTypeByName("Datacenter", datacenter) ?? clunkyTree.First("Datacenter")); _datacenter = dcContent.obj; _vms = (ManagedObjectReference)dcContent.GetProperty("vmFolder"); var clusterContent = clunkyTree.FindTypeByName("ComputeResource", cluster) ?? clunkyTree.First("ComputeResource"); _res = clusterContent.obj; var poolContent = clunkyTree.FindTypeByName("ResourcePool", pool) ?? clunkyTree.FindTypeByReference( (ManagedObjectReference)clusterContent.GetProperty("resourcePool") ); _pool = poolContent.obj; var netSettings = new VimReferences { vim = client, cluster = _res, props = _props, pool = _pool, vmFolder = _vms, UplinkSwitch = _config.Uplink, ExcludeNetworkMask = _config.ExcludeNetworkMask }; if (_config.IsVCenter) { ManagedObjectReference[] subpools = poolContent.GetProperty("resourcePool") as ManagedObjectReference[]; if (subpools != null && subpools.Length > 0) { _pool = subpools.First(); } if (_config.Uplink.StartsWith("nsx.")) { _netman = new NsxNetworkManager( netSettings, _vmCache, _vlanman, _config.Sddc ); } else { var dvs = clunkyTree.FindTypeByName("DistributedVirtualSwitch", _config.Uplink.ToLower()) ?? clunkyTree.First("DistributedVirtualSwitch"); _dvs = dvs?.obj; _dvsuuid = dvs?.GetProperty("uuid").ToString(); netSettings.dvs = dvs?.obj; netSettings.DvsUuid = _dvsuuid; _netman = new DistributedNetworkManager( netSettings, _vmCache, _vlanman ); } } else { var hostContent = clunkyTree.FindType("HostSystem").FirstOrDefault(); if (hostContent != null) { var hostConfig = hostContent.GetProperty("configManager") as HostConfigManager; netSettings.net = hostConfig?.networkSystem; } _netman = new HostNetworkManager( netSettings, _vmCache, _vlanman ); } await _netman.Initialize(); }
static void Main(string[] args) { string url = "https://vcenter.sddc-34-199-139-62.vmwarevmc.com"; string username = ""; string password = Environment.GetEnvironmentVariable("VCENTER_PWD"); string datastoreBrowserKey = "datastoreBrowser-datastore-59"; string path = "[WorkloadDatastore] 834dde5e-cbd6-413d-c0f8-122cc9c14f4d/00000000-0000-0000-0000-000000000000"; string searchRegex = "*.vmdk"; var dsbMOR = new ManagedObjectReference { type = "HostDatastoreBrowser", Value = datastoreBrowserKey }; var vim = new VimPortTypeClient( VimPortTypeClient.EndpointConfiguration.VimPort, $"{url}/sdk" ); var _sic = vim.RetrieveServiceContentAsync( new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" } ).Result; var _props = _sic.propertyCollector; var _session = vim.LoginAsync( _sic.sessionManager, username, password, null ).Result; // search datastore var searchSpec = new HostDatastoreBrowserSearchSpec { matchPattern = new string[] { searchRegex }, }; // var task = vim.SearchDatastore_TaskAsync( var task = vim.SearchDatastoreSubFolders_TaskAsync( dsbMOR, path, searchSpec ).Result; Console.WriteLine($"{task.type} {task.Value}"); Console.WriteLine($"{url}/mob/?moid={task.Value}"); Console.WriteLine(); Console.WriteLine("Sent request, awaiting response..."); Task.Delay(2000).Wait(); var response = vim.RetrievePropertiesAsync( _props, new PropertyFilterSpec[] { new PropertyFilterSpec { propSet = new PropertySpec[] { new PropertySpec { type = "Task", pathSet = new string[] { "info" } } }, objectSet = new ObjectSpec[] { new ObjectSpec { obj = task } } } } ).Result; ObjectContent[] oc = response.returnval; var info = (TaskInfo)oc[0]?.propSet[0]?.val; var results = info?.result as HostDatastoreBrowserSearchResults[]; foreach (var result in results) { foreach (var file in result.file) { Console.WriteLine(result.folderPath, file.path); } } Console.WriteLine("\nDone."); }
public VimProxy(VimPortTypeClient vimPortTypeClient) { _client = vimPortTypeClient; }
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 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); }
private async Task Connect() { // check whether session is expiring if (_session != null && (DateTime.Compare(DateTime.UtcNow, _session.lastActiveTime.AddMinutes(_options.ConnectionRefreshIntervalMinutes)) >= 0)) { _logger.LogDebug("Connect(): Session is more than 20 minutes old"); // renew session because it expires at 30 minutes (maybe 120 minutes on newer vc) _logger.LogInformation($"Connect(): renewing connection to {_options.Host}...[{_options.Username}]"); try { var client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, $"https://{_options.Host}/sdk"); var sic = await client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }); var props = sic.propertyCollector; var session = await client.LoginAsync(sic.sessionManager, _options.Username, _options.Password, null); var oldClient = _client; _client = client; _sic = sic; _props = props; _session = session; await oldClient.CloseAsync(); oldClient.Dispose(); } catch (Exception ex) { // no connection: Failed with Object reference not set to an instance of an object _logger.LogError(0, ex, $"Connect(): Failed with " + ex.Message); _logger.LogError(0, ex, $"Connect(): User: "******"Connect(): CommunicationState.Opened"); ServiceContent sic = _sic; UserSession session = _session; bool isNull = false; if (_sic == null) { sic = await ConnectToHost(_client); isNull = true; } if (_session == null) { session = await ConnectToSession(_client, sic); isNull = true; } if (isNull) { _session = session; _props = sic.propertyCollector; _sic = sic; } try { var x = await _client.RetrieveServiceContentAsync(new ManagedObjectReference { type = "ServiceInstance", Value = "ServiceInstance" }); return; } catch (Exception ex) { _logger.LogError(ex, "Error checking vcenter connection. Disconnecting."); Disconnect(); } } if (_client != null && _client.State == CommunicationState.Faulted) { _logger.LogDebug($"Connect(): https://{_options.Host}/sdk CommunicationState is Faulted."); Disconnect(); } if (_client == null) { try { _logger.LogDebug($"Connect(): Instantiating client https://{_options.Host}/sdk"); var client = new VimPortTypeClient(VimPortTypeClient.EndpointConfiguration.VimPort, $"https://{_options.Host}/sdk"); _logger.LogDebug($"Connect(): client: [{_client}]"); var sic = await ConnectToHost(client); var session = await ConnectToSession(client, sic); _session = session; _props = sic.propertyCollector; _sic = sic; _client = client; } catch (Exception ex) { _logger.LogError(0, ex, $"Connect(): Failed with " + ex.Message); } } }