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 <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); }
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."); }
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); } } }