예제 #1
0
        private async Task <VirtualMachine> GetMachineById(Guid id)
        {
            ManagedObjectReference machineReference = _connectionService.GetMachineById(id);

            if (machineReference == null)
            {
                // lookup reference
                machineReference = await GetVm(id);

                // return null if not found
                if (machineReference == null)
                {
                    return(null);
                }
            }

            if (_client == null)
            {
                return(null);
            }

            // retrieve all machine properties we need
            RetrievePropertiesResponse propertiesResponse = await _client.RetrievePropertiesAsync(
                _props,
                VmFilter(machineReference, "name summary.guest.toolsStatus summary.runtime.host summary.runtime.powerState config.hardware.device"));

            NetVimClient.ObjectContent vm = propertiesResponse.returnval.FirstOrDefault();

            bool vmToolsAvailable = false;

            var toolsStatus = vm.GetProperty("summary.guest.toolsStatus");

            if (toolsStatus != null)
            {
                var virtualMachineToolsStatus = (VirtualMachineToolsStatus)toolsStatus;
                vmToolsAvailable = !(
                    virtualMachineToolsStatus == VirtualMachineToolsStatus.toolsNotInstalled ||
                    virtualMachineToolsStatus == VirtualMachineToolsStatus.toolsNotRunning
                    );
            }

            VirtualMachine machine = new VirtualMachine
            {
                Devices          = vm.GetProperty("config.hardware.device") as VirtualDevice[],
                HostReference    = ((ManagedObjectReference)vm.GetProperty("summary.runtime.host")).Value,
                Id               = id,
                Name             = vm.GetProperty("name") as string,
                Reference        = vm.obj,
                State            = (VirtualMachinePowerState)vm.GetProperty("summary.runtime.powerState") == VirtualMachinePowerState.poweredOn ? "on" : "off",
                VmToolsAvailable = vmToolsAvailable
            };

            return(machine);
        }
예제 #2
0
 public bool VmToolsAvailable(RetrievePropertiesResponse propertiesResponse)
 {
     NetVimClient.ObjectContent[] oc  = propertiesResponse.returnval;
     NetVimClient.ObjectContent   obj = oc[0];
     foreach (DynamicProperty dp in obj.propSet)
     {
         if (dp.val.GetType() == typeof(VirtualMachineSummary))
         {
             VirtualMachineSummary vmSummary = (VirtualMachineSummary)dp.val;
             //check vmware tools status
             var tools_status = vmSummary.guest.toolsStatus;
             if (tools_status == VirtualMachineToolsStatus.toolsNotInstalled || tools_status == VirtualMachineToolsStatus.toolsNotRunning)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
예제 #3
0
        public async Task <string> UploadFileToVm(Guid uuid, string username, string password, string filepath, Stream fileStream)
        {
            _logger.LogDebug("UploadFileToVm called");

            ManagedObjectReference vmReference = vmReference = await GetVm(uuid);

            if (vmReference == null)
            {
                var errorMessage = $"could not upload file, vmReference is null";
                _logger.LogDebug(errorMessage);
                return(errorMessage);
            }
            //retrieve the properties specificied
            RetrievePropertiesResponse response = await _client.RetrievePropertiesAsync(
                _props,
                VmFilter(vmReference));

            NetVimClient.ObjectContent[] oc  = response.returnval;
            NetVimClient.ObjectContent   obj = oc[0];

            foreach (DynamicProperty dp in obj.propSet)
            {
                if (dp.val.GetType() == typeof(VirtualMachineSummary))
                {
                    VirtualMachineSummary vmSummary = (VirtualMachineSummary)dp.val;
                    //check vmware tools status
                    var tools_status = vmSummary.guest.toolsStatus;
                    if (tools_status == VirtualMachineToolsStatus.toolsNotInstalled || tools_status == VirtualMachineToolsStatus.toolsNotRunning)
                    {
                        var errorMessage = $"could not upload file, VM Tools is not running";
                        _logger.LogDebug(errorMessage);
                        return(errorMessage);
                    }

                    // user credentials on the VM
                    NamePasswordAuthentication credentialsAuth = new NamePasswordAuthentication()
                    {
                        interactiveSession = false,
                        username           = username,
                        password           = password
                    };
                    ManagedObjectReference fileManager = new ManagedObjectReference()
                    {
                        type  = "GuestFileManager",
                        Value = "guestOperationsFileManager"
                    };
                    // upload the file
                    GuestFileAttributes fileAttributes = new GuestFileAttributes();
                    var fileTransferUrl = _client.InitiateFileTransferToGuestAsync(fileManager, vmReference, credentialsAuth, filepath, fileAttributes, fileStream.Length, true).Result;

                    // Replace IP address with hostname
                    RetrievePropertiesResponse hostResponse = await _client.RetrievePropertiesAsync(_props, HostFilter(vmSummary.runtime.host, "name"));

                    string hostName = hostResponse.returnval[0].propSet[0].val as string;

                    if (!fileTransferUrl.Contains(hostName))
                    {
                        fileTransferUrl = fileTransferUrl.Replace("https://", "");
                        var s = fileTransferUrl.IndexOf("/");
                        fileTransferUrl = "https://" + hostName + fileTransferUrl.Substring(s);
                    }

                    // http put to url
                    using (var httpClientHandler = new HttpClientHandler())
                    {
                        using (var httpClient = new HttpClient(httpClientHandler))
                        {
                            httpClient.DefaultRequestHeaders.Accept.Clear();
                            using (MemoryStream ms = new MemoryStream())
                            {
                                var timeout = _configuration.GetSection("vmOptions").GetValue("Timeout", 3);
                                httpClient.Timeout = TimeSpan.FromMinutes(timeout);
                                fileStream.CopyTo(ms);
                                var fileContent    = new ByteArrayContent(ms.ToArray());
                                var uploadResponse = await httpClient.PutAsync(fileTransferUrl, fileContent);
                            }
                        }
                    }
                }
            }
            return("");
        }
예제 #4
0
        public string GetPowerState(RetrievePropertiesResponse propertiesResponse)
        {
            VmPowerState State = VmPowerState.off;
            string       state = null;

            NetVimClient.ObjectContent[] oc  = propertiesResponse.returnval;
            NetVimClient.ObjectContent   obj = oc[0];

            foreach (DynamicProperty dp in obj.propSet)
            {
                if (dp.val.GetType() == typeof(VirtualMachineSummary))
                {
                    try
                    {
                        VirtualMachineSummary summary = (VirtualMachineSummary)dp.val;
                        //vm.Name = summary.config.name;
                        //vm.Path = summary.config.vmPathName;
                        //vm.Id = summary.config.uuid;
                        //vm.IpAddress = summary.guest.ipAddress;
                        //vm.Os = summary.guest.guestId;
                        State = (summary.runtime.powerState == VirtualMachinePowerState.poweredOn)
                            ? VmPowerState.running
                            : VmPowerState.off;

                        //vm.IsPoweredOn = (summary.runtime.powerState == VirtualMachinePowerState.poweredOn);
                        //vm.Reference = summary.vm.AsString(); //summary.vm.type + "|" + summary.vm.Value;
                        //vm.Stats = String.Format("{0} | mem-{1}% cpu-{2}%", summary.overallStatus,
                        //    Math.Round(((float)summary.quickStats.guestMemoryUsage / (float)summary.runtime.maxMemoryUsage) * 100, 0),
                        //    Math.Round(((float)summary.quickStats.overallCpuUsage / (float)summary.runtime.maxCpuUsage) * 100, 0));
                        //vm.Annotations = summary.config.annotation.Lines();
                        //vm.ContextNumbers = vm.Annotations.FindOne("context").Value();
                        //vm.ContextNames = vm.Annotations.FindOne("display").Value();
                        //vm.HasGuestAgent = (vm.Annotations.FindOne("guestagent").Value() == "true");
                        //vm.Question = GetQuestion(summary.runtime.question);
                        //vm.Status = "deployed";
                        //if (_tasks.ContainsKey(vm.Id))
                        //{
                        //    var t = _tasks[vm.Id];
                        //    vm.Task = new VmTask { Name= t.Action, WhenCreated = t.WhenCreated, Progress = t.Progress };
                        //}
                    }
                    catch (Exception ex)
                    {
                        _logger.LogDebug(ex.Message);
                    }
                }
            }

            if (State == VmPowerState.running)
            {
                state = "on";
            }
            else if (State == VmPowerState.off)
            {
                state = "off";
            }
            else
            {
                state = "error";
            }
            return(state);
        }