Esempio n. 1
0
        public void ChCBTExec(ManagedObjectReference vm, bool cbtbool)
        {
            VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec();

            spec.changeTrackingEnabledSpecified = true;
            spec.changeTrackingEnabled          = cbtbool;

            ManagedObjectReference taskMor = vimservice.ReconfigVM_Task(vm, spec);
            String res = cb.getServiceUtil().WaitForTask(taskMor);

            if (res.Equals("sucess"))
            {
                VirtualMachineConfigInfo realcfg = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty(vm, "config");
                if (realcfg != null)
                {
                    if (realcfg.changeTrackingEnabled != cbtbool)
                    {
                        throw new Exception("Changeblocktracking updated but config does not reflect it");
                    }
                }
                else
                {
                    throw new Exception("Executed CBT change to " + cbtbool + " but did not succeed in asking update");
                }
            }
            else
            {
                throw new Exception("Not Succesful cbt" + res);
            }
        }
Esempio n. 2
0
        public async Task <Dictionary <string, string> > GetVMConfiguration(VirtualMachine machine, Feature feature)
        {
            VirtualDevice[] devices = machine.Devices;

            VirtualMachineConfigSpec    vmcs  = new VirtualMachineConfigSpec();
            Dictionary <string, string> names = new Dictionary <string, string>();

            switch (feature)
            {
            case Feature.iso:
                IEnumerable <Description> cdroms = devices.OfType <VirtualCdrom>().Select(c => c.deviceInfo);
                foreach (Description d in cdroms)
                {
                    if (d != null)
                    {
                        names.Add(d.label, d.summary);
                    }
                }
                break;

            case Feature.net:
            case Feature.eth:
                IEnumerable <VirtualEthernetCard> cards = devices.OfType <VirtualEthernetCard>();
                foreach (VirtualEthernetCard c in cards)
                {
                    var backingInfo = c.backing;
                    var deviceInfo  = c.deviceInfo;
                    if (backingInfo != null && deviceInfo != null)
                    {
                        if (backingInfo.GetType() == typeof(VirtualEthernetCardDistributedVirtualPortBackingInfo))
                        {
                            var card = backingInfo as VirtualEthernetCardDistributedVirtualPortBackingInfo;      var portGroupKey = card?.port?.portgroupKey;

                            if (!string.IsNullOrEmpty(portGroupKey))
                            {
                                var    network  = _connectionService.GetNetworkByReference(portGroupKey);
                                string cardName = network?.Name;

                                if (!string.IsNullOrEmpty(cardName))
                                {
                                    names.Add(deviceInfo.label, cardName);
                                }
                            }
                        }
                        else if (backingInfo.GetType() == typeof(VirtualEthernetCardNetworkBackingInfo))
                        {
                            var card = backingInfo as VirtualEthernetCardNetworkBackingInfo;
                            names.Add(deviceInfo.label, card.deviceName);
                        }
                        //
                    }
                }
                break;

            default:
                throw new Exception("Invalid request.");
                //break;
            }
            return(names);
        }
Esempio n. 3
0
 public static void MergeGuestInfo(this VirtualMachineConfigSpec vmcs, string settings)
 {
     //constitue options dictionary
     //constitute settings array
     //foreach setting add/update options
     //persist result in annotation
 }
Esempio n. 4
0
        public void ChangeVMNetworkAdapterPortGroup(string vmName, string oldNetworkName, string newNetworkName)
        {
            try {
                VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault();
                if (vm != null)
                {
                    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
                    VirtualDeviceConfigSpec  nicSpec      = new VirtualDeviceConfigSpec();
                    VirtualEthernetCard      nic          = null;
                    VirtualDevice[]          nics         = vm.Config.Hardware.Device.Where(device => device is VMware.Vim.VirtualEthernetCard).Select(vnic => vnic as VirtualEthernetCard).ToArray();
                    nicSpec.Operation = VirtualDeviceConfigSpecOperation.edit;
                    nic = (VirtualEthernetCard)nics.Where(vnic => vnic.DeviceInfo.Summary.Equals(oldNetworkName)).FirstOrDefault();

                    VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
                    Network vNic = new Network(vSphereClient, vm.Runtime.Host);
                    nicBacking.Network    = vNic.MoRef;
                    nicBacking.DeviceName = newNetworkName;

                    if (nic != null)
                    {
                        nic.Backing    = nicBacking;
                        nicSpec.Device = nic;
                    }
                    VirtualDeviceConfigSpec[] nicSpecArray = { nicSpec };
                    vmConfigSpec.DeviceChange = nicSpecArray;
                    vm.ReconfigVM_Task(vmConfigSpec);
                }
            }
            catch (VimException e) {
                lock (m_lock) {
                    WriteLogText(logWriter, e.Message.ToString());
                }
            }
        }
Esempio n. 5
0
 public void RemoveNetworkAdapterFromVM(string vmName, string networkName)
 {
     try {
         VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault();
         if (vm != null)
         {
             VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
             VirtualDeviceConfigSpec  nicSpec      = new VirtualDeviceConfigSpec();
             VirtualEthernetCard      nic          = null;
             VirtualDevice[]          nics         = vm.Config.Hardware.Device.Where(device => device is VMware.Vim.VirtualEthernetCard).Select(vnic => vnic as VirtualEthernetCard).ToArray();
             nicSpec.Operation = VirtualDeviceConfigSpecOperation.remove;
             nic = (VirtualEthernetCard)nics.Where(vnic => vnic.DeviceInfo.Summary.Equals(networkName)).FirstOrDefault();
             if (nic != null)
             {
                 nicSpec.Device = nic;
             }
             VirtualDeviceConfigSpec[] nicSpecArray = { nicSpec };
             vmConfigSpec.DeviceChange = nicSpecArray;
             vm.ReconfigVM_Task(vmConfigSpec);
         }
     } catch (VimException e) {
         lock (m_lock) {
             WriteLogText(logWriter, e.Message.ToString());
         }
     }
 }
Esempio n. 6
0
        internal static VirtualMachineConfigSpec CreateVmConfigSpec(VirtualMachineConfigInfo srcVmCfgInfo, string targetDatastore, string replicaDisplayName)
        {
            VirtualMachineConfigSpec machineConfigSpec = new VirtualMachineConfigSpec();

            machineConfigSpec.alternateGuestName             = srcVmCfgInfo.alternateGuestName;
            machineConfigSpec.annotation                     = srcVmCfgInfo.annotation;
            machineConfigSpec.bootOptions                    = srcVmCfgInfo.bootOptions;
            machineConfigSpec.changeTrackingEnabled          = false;
            machineConfigSpec.changeTrackingEnabledSpecified = true;
            machineConfigSpec.consolePreferences             = srcVmCfgInfo.consolePreferences;
            machineConfigSpec.cpuAffinity                    = srcVmCfgInfo.cpuAffinity;
            machineConfigSpec.cpuFeatureMask                 = VmHelper.GetCpuFeatureMask(srcVmCfgInfo.cpuFeatureMask);
            machineConfigSpec.extraConfig                    = VmHelper.GetExtraConfig(srcVmCfgInfo.extraConfig);
            machineConfigSpec.files = new VirtualMachineFileInfo()
            {
                vmPathName        = VmHelper.GetBracketedName(targetDatastore),
                snapshotDirectory = VmHelper.GetBracketedName(targetDatastore)
            };
            machineConfigSpec.flags             = srcVmCfgInfo.flags;
            machineConfigSpec.ftInfo            = srcVmCfgInfo.ftInfo;
            machineConfigSpec.guestId           = srcVmCfgInfo.guestId;
            machineConfigSpec.memoryAffinity    = srcVmCfgInfo.memoryAffinity;
            machineConfigSpec.memoryMB          = (long)srcVmCfgInfo.hardware.memoryMB;
            machineConfigSpec.memoryMBSpecified = true;
            machineConfigSpec.name                     = replicaDisplayName;
            machineConfigSpec.networkShaper            = srcVmCfgInfo.networkShaper;
            machineConfigSpec.npivWorldWideNameType    = srcVmCfgInfo.npivWorldWideNameType;
            machineConfigSpec.numCPUs                  = srcVmCfgInfo.hardware.numCPU;
            machineConfigSpec.numCPUsSpecified         = true;
            machineConfigSpec.powerOpInfo              = srcVmCfgInfo.defaultPowerOps;
            machineConfigSpec.swapPlacement            = srcVmCfgInfo.swapPlacement;
            machineConfigSpec.tools                    = srcVmCfgInfo.tools;
            machineConfigSpec.vAppConfig               = VmHelper.VmConfigInfoToVmConfigSpec(srcVmCfgInfo.vAppConfig);
            machineConfigSpec.vAssertsEnabled          = srcVmCfgInfo.vAssertsEnabled;
            machineConfigSpec.vAssertsEnabledSpecified = true;
            machineConfigSpec.version                  = srcVmCfgInfo.version;
            machineConfigSpec.deviceChange             = VmHelper.CreateVmDeviceSpecs(srcVmCfgInfo.hardware);
            if (srcVmCfgInfo.version != "vmx-04")
            {
                machineConfigSpec.cpuHotAddEnabled               = srcVmCfgInfo.cpuHotAddEnabled;
                machineConfigSpec.cpuHotAddEnabledSpecified      = true;
                machineConfigSpec.cpuHotRemoveEnabled            = srcVmCfgInfo.cpuHotRemoveEnabled;
                machineConfigSpec.cpuHotRemoveEnabledSpecified   = true;
                machineConfigSpec.memoryHotAddEnabled            = srcVmCfgInfo.memoryHotAddEnabled;
                machineConfigSpec.memoryHotAddEnabledSpecified   = true;
                machineConfigSpec.npivDesiredNodeWwns            = srcVmCfgInfo.npivDesiredNodeWwns;
                machineConfigSpec.npivDesiredNodeWwnsSpecified   = true;
                machineConfigSpec.npivDesiredPortWwns            = srcVmCfgInfo.npivDesiredPortWwns;
                machineConfigSpec.npivDesiredPortWwnsSpecified   = true;
                machineConfigSpec.npivNodeWorldWideName          = srcVmCfgInfo.npivNodeWorldWideName;
                machineConfigSpec.npivOnNonRdmDisks              = srcVmCfgInfo.npivOnNonRdmDisks;
                machineConfigSpec.npivOnNonRdmDisksSpecified     = true;
                machineConfigSpec.npivPortWorldWideName          = srcVmCfgInfo.npivPortWorldWideName;
                machineConfigSpec.npivTemporaryDisabled          = srcVmCfgInfo.npivTemporaryDisabled;
                machineConfigSpec.npivTemporaryDisabledSpecified = true;
            }
            return(machineConfigSpec);
        }
Esempio n. 7
0
        public TaskInfoState ReconfigVM(VirtualMachineConfigSpec spec)
        {
            ManagedObjectReference morTask = _vimService.ReconfigVM_Task(_morThis, spec);
            MyVMTask      myTask           = new MyVMTask(_vimService, _pc, morTask);
            TaskInfo      ti    = null;
            TaskInfoState state = myTask.Wait(3000, -1, out ti);

            return(state);
        }
Esempio n. 8
0
        public async Task <Vm> Deploy(VmTemplate template)
        {
            Vm vm = null;

            await Connect();

            _logger.LogDebug("deploy: validate portgroups...");
            await _netman.Provision(template);

            _logger.LogDebug("deploy: transform template...");
            //var transformer = new VCenterTransformer { DVSuuid = _dvsuuid };
            VirtualMachineConfigSpec vmcs = Transform.TemplateToVmSpec(
                template,
                _config.VmStore.Replace("{host}", _hostPrefix),
                _dvsuuid
                );

            _logger.LogDebug("deploy: create vm...");
            ManagedObjectReference task = await _vim.CreateVM_TaskAsync(_vms, vmcs, _pool, null);

            TaskInfo info = await WaitForVimTask(task);

            if (info.state == TaskInfoState.success)
            {
                _logger.LogDebug("deploy: load vm...");
                await Task.Delay(200);

                vm = await GetVirtualMachine((ManagedObjectReference)info.result);

                _logger.LogDebug("deploy: create snapshot...");
                task = await _vim.CreateSnapshot_TaskAsync(
                    vm.AsVim(),
                    "Root Snap",
                    "Created by TopoMojo Deploy at " + DateTime.UtcNow.ToString("s") + "Z",
                    false, false);

                info = await WaitForVimTask(task);

                if (template.AutoStart && info.state == TaskInfoState.success)
                {
                    _logger.LogDebug("deploy: start vm...");
                    vm = await Start(vm.Id);
                }
            }
            else
            {
                throw new Exception(info.error.localizedMessage);
            }
            return(vm);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string      strResult    = "";
            Servers     oServer      = new Servers(0, dsn);
            OnDemand    oOnDemand    = new OnDemand(0, dsn);
            IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn);

            oVMWare = new VMWare(0, dsn);
            string strConnect = oVMWare.ConnectDEBUG("https://ohcleutl4001/sdk", 3, "Dalton");

            if (strConnect == "")
            {
                VimService             _service       = oVMWare.GetService();
                ServiceContent         _sic           = oVMWare.GetSic();
                string                 strName        = "txpv00001a";
                ManagedObjectReference _vm_boot_order = oVMWare.GetVM(strName);

                OptionValue oValue = new OptionValue();
                oValue.key = "bios.bootDeviceClasses";
                // Set the PXE boot
                oValue.value = "allow:net";
                // Remove the PXE boot
                oValue.value = "";
                VirtualMachineConfigSpec _cs_boot_order = new VirtualMachineConfigSpec();
                _cs_boot_order.extraConfig = new OptionValue[] { oValue };

                ManagedObjectReference _task_boot_order = _service.ReconfigVM_Task(_vm_boot_order, _cs_boot_order);
                TaskInfo _inf_boot_order = (TaskInfo)oVMWare.getObjectProperty(_task_boot_order, "info");
                while (_inf_boot_order.state == TaskInfoState.running)
                {
                    _inf_boot_order = (TaskInfo)oVMWare.getObjectProperty(_task_boot_order, "info");
                }
                if (_inf_boot_order.state == TaskInfoState.success)
                {
                    strResult = "PXE Boot Forced";
                }
                else
                {
                    strResult = "PXE Boot NOT Forced";
                }
                Response.Write(strResult);
            }
            else
            {
                Response.Write("LOGIN error");
            }
        }
Esempio n. 10
0
 public static void AddBootOption(this VirtualMachineConfigSpec vmcs, int delay)
 {
     if (delay != 0)
     {
         vmcs.bootOptions = new VirtualMachineBootOptions();
         if (delay > 0)
         {
             vmcs.bootOptions.bootDelay          = delay * 1000;
             vmcs.bootOptions.bootDelaySpecified = true;
         }
         if (delay < 0)
         {
             vmcs.bootOptions.enterBIOSSetup          = true;
             vmcs.bootOptions.enterBIOSSetupSpecified = true;
         }
     }
 }
Esempio n. 11
0
        public static void AddGuestInfo(this VirtualMachineConfigSpec vmcs, string[] list)
        {
            List <OptionValue> options = new List <OptionValue>();

            foreach (string item in list)
            {
                OptionValue option = new OptionValue();
                int         x      = item.IndexOf('=');
                if (x > 0)
                {
                    option.key = item.Substring(0, x).Replace(" ", "").Trim();
                    if (!option.key.StartsWith("guestinfo."))
                    {
                        option.key = "guestinfo." + option.key;
                    }
                    option.value = item.Substring(x + 1).Trim();
                    options.Add(option);
                }
            }
            vmcs.extraConfig = options.ToArray();
        }
Esempio n. 12
0
        public void AddNetworkAdapterToVM(string vmName, string networkName)
        {
            try {
                VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault();
                if (vm != null)
                {
                    Network vNic = new Network(vSphereClient, vm.Runtime.Host);

                    VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
                    if (networkName != null)
                    {
                        nicSpec.Operation = VirtualDeviceConfigSpecOperation.add;
                        VirtualEthernetCard nic = new VirtualVmxnet();
                        VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
                        nicBacking.Network    = vNic.MoRef;
                        nicBacking.DeviceName = networkName;
                        nic.AddressType       = "generated";
                        nic.Backing           = nicBacking;
                        nic.Key        = 4;
                        nicSpec.Device = nic;
                    }

                    VirtualDeviceConfigSpec[] specs      = { nicSpec };
                    VirtualMachineConfigSpec  vmConfSpec = new VirtualMachineConfigSpec();
                    vmConfSpec.DeviceChange = specs;

                    vm.ReconfigVM_Task(vmConfSpec);
                }
            }
            catch (VimException e) {
                lock (m_lock) {
                    WriteLogText(logWriter, e.Message.ToString());
                }
            } catch (Exception e) {
                lock (m_lock) {
                    WriteLogText(logWriter, e.Message.ToString());
                }
            }
        }
Esempio n. 13
0
        protected virtual IVimVm _CreateVm()
        {
            this._Context.SetLowLevelState("CreatingVm");
            IVimDatastore datastoreByUrl = this._ESXHost.GetDatastoreByUrl(this._Context.JobInfoWrapper.DataStoreUrl);
            string        replicaVmName  = this._Context.JobInfoWrapper.VmName;

            if (datastoreByUrl.IsFolderOnRootExist(replicaVmName, this._Context.ESXHost.ClientCtx))
            {
                throw new OculiServiceServiceException(0, string.Format("The folder for the vm {0} already exists on the datastore {1}", (object)replicaVmName, (object)datastoreByUrl.BracketedName));
            }
            VirtualMachineConfigSpec compatibleConfigSpec = this._Context.ESXHost.SourceVm().GetCompatibleConfigSpec(datastoreByUrl.Name, this._Context.JobInfoWrapper.VmName);

            compatibleConfigSpec.numCPUs = Math.Min((int)this._ESXHost.GetNumberCPU(), compatibleConfigSpec.numCPUs);
            long num = Math.Min(this._ESXHost.GetMemory() / 1048576L, compatibleConfigSpec.memoryMB);

            compatibleConfigSpec.memoryMB = num - num % 4L;
            this._Logger.FormatInformation(" VM will have {0} CPUs and {1}MB memory.", (object)compatibleConfigSpec.numCPUs, (object)compatibleConfigSpec.memoryMB);
            Dictionary <string, string> networkMap = new Dictionary <string, string>();

            ((IEnumerable <VirtualSwitchMapping>) this._Context.JobInfoWrapper.VirtualSwitchMapping).ForEach <VirtualSwitchMapping>((System.Action <VirtualSwitchMapping>)(vsm => networkMap.Add(vsm.SourceVirtualSwitch.Label, vsm.TargetVirtualSwitch.Label)));
            Dictionary <string, string> distributedPortGroupMap = this._Context.ESXHost.SourceVm().GetHostAndProperties().GetDistributedVirtualPortgroups();

            ((IEnumerable <VirtualDeviceConfigSpec>)compatibleConfigSpec.deviceChange).Where <VirtualDeviceConfigSpec>((Func <VirtualDeviceConfigSpec, bool>)(vdcs =>
            {
                if (vdcs.device is VirtualEthernetCard)
                {
                    return(vdcs.device.backing is VirtualEthernetCardDistributedVirtualPortBackingInfo);
                }
                return(false);
            })).ForEach <VirtualDeviceConfigSpec>((System.Action <VirtualDeviceConfigSpec>)(vdcs =>
            {
                string str1 = distributedPortGroupMap[((VirtualEthernetCardDistributedVirtualPortBackingInfo)vdcs.device.backing).port.portgroupKey];
                int length  = str1.IndexOf(" (", 0);
                string str2 = str1.Substring(0, length);
                vdcs.device.deviceInfo.summary = str2;
            }));
            return(this._ESXHost.CreateVmWithNetworkMapping(compatibleConfigSpec, networkMap, this._Context.ESXHost.ClientCtx));
        }
Esempio n. 14
0
        public static void AddCpu(this VirtualMachineConfigSpec vmcs, string cpu)
        {
            string[] p = cpu.Split('x');
            int      sockets = 1, coresPerSocket = 1;

            if (!Int32.TryParse(p[0], out sockets))
            {
                sockets = 1;
            }

            if (p.Length > 1)
            {
                if (!Int32.TryParse(p[1], out coresPerSocket))
                {
                    coresPerSocket = 1;
                }
            }

            vmcs.numCPUs                    = sockets * coresPerSocket;
            vmcs.numCPUsSpecified           = true;
            vmcs.numCoresPerSocket          = coresPerSocket;
            vmcs.numCoresPerSocketSpecified = true;
        }
Esempio n. 15
0
        /// <summary>
        /// Reconfig the virtual machine.
        /// </summary>
        private void reconfigVirtualMachine()
        {
            Console.WriteLine("ReConfigure The Virtual Machine ..........");
            VirtualMachineFileInfo vmFileInfo
                = new VirtualMachineFileInfo();

            vmFileInfo.logDirectory      = "[" + getDataStore() + "]" + getVmName();
            vmFileInfo.snapshotDirectory = "[" + getDataStore() + "]" + getVmName();
            vmFileInfo.suspendDirectory  = "[" + getDataStore() + "]" + getVmName();
            vmFileInfo.vmPathName        = "[" + getDataStore()
                                           + "]" + getVmName() + "/" + getVmName() + ".vmx";

            VirtualMachineConfigSpec vmConfigSpec
                = new VirtualMachineConfigSpec();

            vmConfigSpec.files = vmFileInfo;

            ManagedObjectReference taskmor
                = _service.ReconfigVM_Task(
                      getVmMor(getVmName()), vmConfigSpec);

            Object[] result = cb.getServiceUtil().WaitForValues(
                taskmor, new String[] { "info.state", "info.error" },
                new String[] { "state" },
                new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error } }
                );

            if (result[0].Equals(TaskInfoState.success))
            {
                Console.WriteLine("ReConfigure The Virtual Machine .......... Done");
            }
            else
            {
                Console.WriteLine("Some Exception While Reconfiguring The VM " + result[0]);
            }
        }
Esempio n. 16
0
        public static VirtualMachineConfigSpec TemplateToVmSpec(VmTemplate template, string datastore, string dvsuuid)
        {
            int key = -101, idekey = 200;
            VirtualMachineConfigSpec       vmcs = new VirtualMachineConfigSpec();
            List <VirtualDeviceConfigSpec> devices = new List <VirtualDeviceConfigSpec>();

            vmcs.name        = template.Name;
            vmcs.extraConfig = GetExtraConfig(template);
            vmcs.AddRam(template.Ram);
            vmcs.AddCpu(template.Cpu);
            vmcs.AddBootOption(Math.Max(template.Delay, 10));
            vmcs.version = (template.Version.HasValue()) ? template.Version : null;
            vmcs.guestId = (template.Guest.HasValue() ? template.Guest : "other");
            if (!vmcs.guestId.EndsWith("Guest"))
            {
                vmcs.guestId += "Guest";
            }
            if (datastore.HasValue())
            {
                vmcs.files = new VirtualMachineFileInfo {
                    vmPathName = $"{datastore}/{template.Name}/{template.Name}.vmx"
                };
            }

            //can't actually be applied via ExtraConfig
            if (template.GuestSettings.Length > 0 &&
                template.GuestSettings.Any(s => s.Key == "vhv.enable" && s.Value == "true"))
            {
                vmcs.nestedHVEnabled          = true;
                vmcs.nestedHVEnabledSpecified = true;
            }

            //video card
            devices.Add(GetVideoController(ref key, template.VideoRam));

            //floppy disk
            if (template.Floppy.HasValue())
            {
                devices.Add(GetFloppy(ref key, template.Floppy));
            }

            //nics
            foreach (VmNet nic in template.Eth)
            {
                devices.Add(GetEthernetAdapter(ref key, nic, dvsuuid));
            }

            // //network serial port
            // if (!String.IsNullOrEmpty(template.FindOne("nsp").Value()))
            //     devices.Add(GetNetworkSerialPort(ref key, template.FindOne("nsp").Value()));

            //controller
            int controllerKey = 0, count = 0;

            foreach (VmDisk disk in template.Disks)
            {
                if (controllerKey == 0)
                {
                    if (disk.Controller == "ide")
                    {
                        controllerKey = idekey;
                    }
                    else
                    {
                        VirtualDeviceConfigSpec controller = GetSCSIController(ref key, disk.Controller);
                        controllerKey = controller.device.key;
                        devices.Add(controller);
                    }
                }
                devices.Add(GetDisk(ref key, disk.Path, controllerKey, count++));
            }


            //iso
            devices.Add(GetCdrom(ref key, idekey, (template.Iso.HasValue() ? template.Iso : "[iso] null.iso")));

            //add all devices to spec
            vmcs.deviceChange = devices.ToArray();

            return(vmcs);
        }
        public void ConnectIso( string isoLocation )
        {
            const string remotePath = "/Temp";

            UploadArtifact( isoLocation, remotePath );

            _virtualMachine.UpdateViewData();

            VirtualCdrom cd = _virtualMachine.Config.Hardware.Device.FirstOrDefault( d => d is VirtualCdrom ) as VirtualCdrom;

            if ( cd == null )
            {
                throw new ApplicationException( "CD is null" );
            }

            VirtualCdromIsoBackingInfo newBacking = new VirtualCdromIsoBackingInfo
                                                        {
                                                            FileName = string.Format( "[{0}] {1}", "datastore1", remotePath )
                                                        };
            cd.Backing = newBacking;
            cd.Connectable.StartConnected = true;
            cd.Connectable.Connected = true;

            VirtualDeviceConfigSpec deviceSpec = new VirtualDeviceConfigSpec
                                                     {
                                                         Device = cd,
                                                         Operation = VirtualDeviceConfigSpecOperation.edit
                                                     };

            VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec
                                                  {
                                                      DeviceChange = new[] {deviceSpec}
                                                  };

            _virtualMachine.ReconfigVM( vmSpec );
        }
Esempio n. 18
0
        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);
        }
 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();
     }
 }
Esempio n. 20
0
        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");
            }
        }
Esempio n. 21
0
        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");
            }
        }
Esempio n. 22
0
       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);   
 }
Esempio n. 23
0
 public static void AddRam(this VirtualMachineConfigSpec vmcs, int ram)
 {
     vmcs.memoryMB          = (ram > 0) ? ram * 1024 : 1024;
     vmcs.memoryMBSpecified = true;
 }
Esempio n. 24
0
        //id, feature (iso, net, boot, guest), label, value
        public async Task <Vm> ReconfigureVm(string id, string feature, string label, string newvalue)
        {
            await Connect();

            int index = 0;

            if (int.TryParse(label, out index))
            {
                label = "";
            }

            Vm vm = _vmCache[id];
            RetrievePropertiesResponse response = await _vim.RetrievePropertiesAsync(
                _props,
                FilterFactory.VmFilter(vm.AsVim(), "config"));

            ObjectContent[] oc = response.returnval;

            VirtualMachineConfigInfo config = (VirtualMachineConfigInfo)oc[0].GetProperty("config");
            VirtualMachineConfigSpec vmcs   = new VirtualMachineConfigSpec();

            switch (feature)
            {
            case "iso":
                VirtualCdrom cdrom = (VirtualCdrom)((label.HasValue())
                        ? config.hardware.device.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : config.hardware.device.OfType <VirtualCdrom>().ToArray()[index]);

                if (cdrom != null)
                {
                    if (cdrom.backing.GetType() != typeof(VirtualCdromIsoBackingInfo))
                    {
                        cdrom.backing = new VirtualCdromIsoBackingInfo();
                    }

                    ((VirtualCdromIsoBackingInfo)cdrom.backing).fileName = newvalue;
                    cdrom.connectable = new VirtualDeviceConnectInfo
                    {
                        connected      = true,
                        startConnected = true
                    };

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = cdrom,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case "net":
            case "eth":
                VirtualEthernetCard card = (VirtualEthernetCard)((label.HasValue())
                        ? config.hardware.device.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : config.hardware.device.OfType <VirtualEthernetCard>().ToArray()[index]);

                if (card != null)
                {
                    if (newvalue.StartsWith("_none_"))
                    {
                        card.connectable = new VirtualDeviceConnectInfo()
                        {
                            connected      = false,
                            startConnected = false,
                        };
                    }
                    else
                    {
                        _netman.UpdateEthernetCardBacking(card, newvalue);
                        card.connectable.connected = true;
                    }

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = card,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case "boot":
                int delay = 0;
                if (Int32.TryParse(newvalue, out delay))
                {
                    vmcs.AddBootOption(delay);
                }
                break;

            case "guest":
                if (newvalue.HasValue() && !newvalue.EndsWith("\n"))
                {
                    newvalue += "\n";
                }
                vmcs.annotation = config.annotation + newvalue;
                if (vm.State == VmPowerState.Running && vmcs.annotation.HasValue())
                {
                    vmcs.AddGuestInfo(Regex.Split(vmcs.annotation, "\r\n|\r|\n"));
                }
                break;

            default:
                throw new Exception("Invalid change request.");
                //break;
            }

            ManagedObjectReference task = await _vim.ReconfigVM_TaskAsync(vm.AsVim(), vmcs);

            TaskInfo info = await WaitForVimTask(task);

            if (info.state == TaskInfoState.error)
            {
                throw new Exception(info.error.localizedMessage);
            }
            return(await GetVirtualMachine(vm.AsVim()));
        }
Esempio n. 25
0
        public VirtualMachineConfigSpec createVmConfigSpec(String vmName,

                                                           String datastoreName,

                                                           int diskSizeMB,

                                                           ManagedObjectReference computeResMor,

                                                           ManagedObjectReference hostMor)

        {
            ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor);

            VirtualDevice[] defaultDevices = getDefaultDevices(computeResMor, hostMor);

            VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();



            String networkName = null;

            if (configTarget.network != null)

            {
                for (int i = 0; i < configTarget.network.Length; i++)

                {
                    VirtualMachineNetworkInfo netInfo = configTarget.network[i];

                    NetworkSummary netSummary = netInfo.network;

                    if (netSummary.accessible)

                    {
                        networkName = netSummary.name;

                        break;
                    }
                }
            }

            ManagedObjectReference datastoreRef = null;

            if (datastoreName != null)

            {
                Boolean flag = false;

                for (int i = 0; i < configTarget.datastore.Length; i++)

                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];

                    DatastoreSummary dsSummary = vdsInfo.datastore;

                    if (dsSummary.name.Equals(datastoreName))

                    {
                        flag = true;

                        if (dsSummary.accessible)

                        {
                            datastoreName = dsSummary.name;

                            datastoreRef = dsSummary.datastore;
                        }

                        else

                        {
                            throw new Exception("Specified Datastore is not accessible");
                        }

                        break;
                    }
                }

                if (!flag)

                {
                    throw new Exception("Specified Datastore is not Found");
                }
            }

            else

            {
                Boolean flag = false;

                for (int i = 0; i < configTarget.datastore.Length; i++)

                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];

                    DatastoreSummary dsSummary = vdsInfo.datastore;

                    if (dsSummary.accessible)

                    {
                        datastoreName = dsSummary.name;

                        datastoreRef = dsSummary.datastore;

                        flag = true;

                        break;
                    }
                }

                if (!flag)

                {
                    throw new Exception("No Datastore found on host");
                }
            }

            String datastoreVolume = getVolumeName(datastoreName);

            VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();

            vmfi.vmPathName = datastoreVolume;

            configSpec.files = vmfi;

            // Add a scsi controller

            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.noSharing;

            String ctlrType = scsiCtrl.GetType().Name;



            // Find the IDE controller

            VirtualDevice ideCtlr = null;

            for (int di = 0; di < defaultDevices.Length; di++)

            {
                if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController"))

                {
                    ideCtlr = defaultDevices[di];

                    break;
                }
            }



            // Add a floppy

            VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec();

            floppySpec.operation = VirtualDeviceConfigSpecOperation.add;

            floppySpec.operationSpecified = true;

            VirtualFloppy floppy = new VirtualFloppy();

            VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo();

            flpBacking.deviceName = "/dev/fd0";

            floppy.backing = flpBacking;

            floppy.key = 3;

            floppySpec.device = floppy;



            // Add a cdrom based on a physical device

            VirtualDeviceConfigSpec cdSpec = null;



            if (ideCtlr != null)

            {
                cdSpec = new VirtualDeviceConfigSpec();

                cdSpec.operation = VirtualDeviceConfigSpecOperation.add;

                cdSpec.operationSpecified = true;

                VirtualCdrom cdrom = new VirtualCdrom();

                VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo();

                cdDeviceBacking.datastore = datastoreRef;

                cdDeviceBacking.fileName = datastoreVolume + "testcd.iso";

                cdrom.backing = cdDeviceBacking;

                cdrom.key = 20;

                cdrom.controllerKey = ideCtlr.key;

                cdrom.controllerKeySpecified = true;

                cdrom.unitNumberSpecified = true;

                cdrom.unitNumber = 0;

                cdSpec.device = cdrom;
            }



            // Create a new disk - file based - for the vm

            VirtualDeviceConfigSpec diskSpec = null;

            diskSpec = createVirtualDisk(datastoreName, diskCtlrKey, datastoreRef, diskSizeMB);



            // Add a NIC. the network Name must be set as the device name to create the NIC.

            VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();

            if (networkName != null)

            {
                nicSpec.operation = VirtualDeviceConfigSpecOperation.add;

                nicSpec.operationSpecified = true;

                VirtualEthernetCard nic = new VirtualPCNet32();

                VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();

                nicBacking.deviceName = networkName;

                nic.addressType = "generated";

                nic.backing = nicBacking;

                nic.key = 4;

                nicSpec.device = nic;
            }



            var deviceConfigSpec = new List <VirtualDeviceConfigSpec>();

            deviceConfigSpec.Add(scsiCtrlSpec);

            deviceConfigSpec.Add(floppySpec);

            deviceConfigSpec.Add(diskSpec);

            deviceConfigSpec.Add(nicSpec);



            if (ideCtlr != null)

            {
                deviceConfigSpec.Add(cdSpec);
            }



            configSpec.deviceChange = deviceConfigSpec.ToArray();

            return(configSpec);
        }
Esempio n. 26
0
        public async Task <TaskInfo> ReconfigureVm(Guid id, Feature feature, string label, string newvalue)
        {
            VirtualMachine machine = await GetMachineById(id);

            ManagedObjectReference vmReference = machine.Reference;

            VirtualDevice[]          devices = machine.Devices;
            VirtualMachineConfigSpec vmcs    = new VirtualMachineConfigSpec();

            switch (feature)
            {
            case Feature.iso:
                VirtualCdrom cdrom = (VirtualCdrom)((label.HasValue())
                        ? devices.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : devices.OfType <VirtualCdrom>().FirstOrDefault());

                if (cdrom != null)
                {
                    if (cdrom.backing.GetType() != typeof(VirtualCdromIsoBackingInfo))
                    {
                        cdrom.backing = new VirtualCdromIsoBackingInfo();
                    }

                    ((VirtualCdromIsoBackingInfo)cdrom.backing).datastore = (await GetDatastoreByName(_options.DsName)).Reference;
                    ((VirtualCdromIsoBackingInfo)cdrom.backing).fileName  = newvalue;
                    cdrom.connectable = new VirtualDeviceConnectInfo
                    {
                        connected      = true,
                        startConnected = true
                    };

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = cdrom,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case Feature.net:
            case Feature.eth:
                VirtualEthernetCard card = (VirtualEthernetCard)((label.HasValue())
                        ? devices.Where(o => o.deviceInfo.label == label).SingleOrDefault()
                        : devices.OfType <VirtualEthernetCard>().FirstOrDefault());

                if (card != null)
                {
                    Network network = _connectionService.GetNetworkByName(newvalue);

                    if (network.IsDistributed)
                    {
                        card.backing = new VirtualEthernetCardDistributedVirtualPortBackingInfo
                        {
                            port = new DistributedVirtualSwitchPortConnection
                            {
                                portgroupKey = network.Reference,
                                switchUuid   = network.SwitchId
                            }
                        };
                    }
                    else
                    {
                        card.backing = new VirtualEthernetCardNetworkBackingInfo
                        {
                            deviceName = newvalue
                        };
                    }

                    //if (card.backing is VirtualEthernetCardNetworkBackingInfo)
                    //    ((VirtualEthernetCardNetworkBackingInfo)card.backing).deviceName = newvalue;

                    //if (card.backing is VirtualEthernetCardDistributedVirtualPortBackingInfo)
                    //    ((VirtualEthernetCardDistributedVirtualPortBackingInfo)card.backing).port.portgroupKey = newvalue;

                    card.connectable = new VirtualDeviceConnectInfo()
                    {
                        connected      = true,
                        startConnected = true,
                    };

                    vmcs.deviceChange = new VirtualDeviceConfigSpec[] {
                        new VirtualDeviceConfigSpec {
                            device             = card,
                            operation          = VirtualDeviceConfigSpecOperation.edit,
                            operationSpecified = true
                        }
                    };
                }
                break;

            case Feature.boot:
                int delay = 0;
                if (Int32.TryParse(newvalue, out delay))
                {
                    vmcs.AddBootOption(delay);
                }
                break;

            //case Feature.guest:
            //    if (newvalue.HasValue() && !newvalue.EndsWith("\n"))
            //        newvalue += "\n";
            //    vmcs.annotation = config.annotation + newvalue;
            //    if (vm.State == VmPowerState.running && vmcs.annotation.HasValue())
            //        vmcs.AddGuestInfo(Regex.Split(vmcs.annotation, "\r\n|\r|\n"));
            //    break;

            default:
                throw new Exception("Invalid change request.");
                //break;
            }

            ManagedObjectReference task = await _client.ReconfigVM_TaskAsync(vmReference, vmcs);

            TaskInfo info = await WaitForVimTask(task);

            if (info.state == TaskInfoState.error)
            {
                throw new Exception(info.error.localizedMessage);
            }
            return(info);
        }
Esempio n. 27
0
        public byte[] SerializeVMConfig(object vmConfig)
        {
            var sourceConfig = vmConfig as VirtualMachineConfigInfo;

            if (sourceConfig == null)
            {
                throw new ArgumentException($"{nameof(vmConfig)} must be of type VirtualMachineConfigInfo");
            }

            var configSpec = new VirtualMachineConfigSpec
            {
                name                = sourceConfig.name,
                version             = sourceConfig.version,
                guestId             = sourceConfig.guestId,
                alternateGuestName  = sourceConfig.alternateGuestName,
                files               = sourceConfig.files,
                tools               = sourceConfig.tools,
                flags               = sourceConfig.flags,
                consolePreferences  = null,
                powerOpInfo         = sourceConfig.defaultPowerOps,
                numCPUs             = sourceConfig.hardware.numCPU,
                memoryMB            = sourceConfig.hardware.memoryMB,
                cpuHotAddEnabled    = sourceConfig.cpuHotAddEnabled,
                memoryHotAddEnabled = sourceConfig.memoryHotAddEnabled,
                numCoresPerSocket   = sourceConfig.hardware.numCoresPerSocket,
                cpuFeatureMask      = sourceConfig.cpuFeatureMask.Select(info => new VirtualMachineCpuIdInfoSpec {
                    operation = ArrayUpdateOperation.add, info = info
                }).ToArray(),
                deviceChange = sourceConfig.hardware.device.Where(
                    device =>
                    !(
                        device is VirtualIDEController ||
                        device is VirtualPS2Controller ||
                        device is VirtualPCIController ||
                        device is VirtualSIOController ||
                        device is VirtualMachineVMCIDevice ||
                        device is VirtualKeyboard ||
                        device is VirtualPointingDevice
                        )
                    ).Select(
                    device => new VirtualDeviceConfigSpec
                {
                    operation = VirtualDeviceConfigSpecOperation.add,
                    device    = device,
                }).ToArray(),
                cpuAllocation    = sourceConfig.cpuAllocation,
                memoryAllocation = sourceConfig.memoryAllocation,
                cpuAffinity      = null,
                memoryAffinity   = null,
                networkShaper    = null,
                bootOptions      = null
            };

            byte[] result = null;
            using (var memStream = new MemoryStream())
            {
                using (var zippedStream = new DeflateStream(memStream, CompressionMode.Compress))
                    using (var writeStream = new StreamWriter(zippedStream))
                    {
                        writeStream.Write(JsonConvert.SerializeObject(configSpec));
                    }
                result = memStream.ToArray();
            }

            return(result);
        }
 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();
     }
 }
Esempio n. 29
0
        public VirtualMachineConfigSpec createVmConfigSpec(String vmName,
                                                        String datastoreName,
                                                        int diskSizeMB,
                                                        ManagedObjectReference computeResMor,
                                                        ManagedObjectReference hostMor)
        {

            ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor);
            VirtualDevice[] defaultDevices = getDefaultDevices(computeResMor, hostMor);
            VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();

            String networkName = null;
            if (configTarget.network != null)
            {
                for (int i = 0; i < configTarget.network.Length; i++)
                {
                    VirtualMachineNetworkInfo netInfo = configTarget.network[i];
                    NetworkSummary netSummary = netInfo.network;
                    if (netSummary.accessible)
                    {
                        networkName = netSummary.name;
                        break;
                    }
                }
            }
            ManagedObjectReference datastoreRef = null;
            if (datastoreName != null)
            {
                Boolean flag = false;
                for (int i = 0; i < configTarget.datastore.Length; i++)
                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];
                    DatastoreSummary dsSummary = vdsInfo.datastore;
                    if (dsSummary.name.Equals(datastoreName))
                    {
                        flag = true;
                        if (dsSummary.accessible)
                        {
                            datastoreName = dsSummary.name;
                            datastoreRef = dsSummary.datastore;
                        }
                        else
                        {
                            throw new Exception("Specified Datastore is not accessible");
                        }
                        break;
                    }
                }
                if (!flag)
                {
                    throw new Exception("Specified Datastore is not Found");
                }
            }
            else
            {
                Boolean flag = false;
                for (int i = 0; i < configTarget.datastore.Length; i++)
                {
                    VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i];
                    DatastoreSummary dsSummary = vdsInfo.datastore;
                    if (dsSummary.accessible)
                    {
                        datastoreName = dsSummary.name;
                        datastoreRef = dsSummary.datastore;
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    throw new Exception("No Datastore found on host");
                }
            }
            String datastoreVolume = getVolumeName(datastoreName);
            VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();
            vmfi.vmPathName = datastoreVolume;
            configSpec.files = vmfi;
            // Add a scsi controller
            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.noSharing;
            String ctlrType = scsiCtrl.GetType().Name;


            // Find the IDE controller
            VirtualDevice ideCtlr = null;
            for (int di = 0; di < defaultDevices.Length; di++)
            {
                if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController"))
                {
                    ideCtlr = defaultDevices[di];
                    break;
                }
            }

            // Add a floppy
            VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec();
            floppySpec.operation = VirtualDeviceConfigSpecOperation.add;
            floppySpec.operationSpecified = true;
            VirtualFloppy floppy = new VirtualFloppy();
            VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo();
            flpBacking.deviceName = "/dev/fd0";
            floppy.backing = flpBacking;
            floppy.key = 3;
            floppySpec.device = floppy;

            // Add a cdrom based on a physical device
            VirtualDeviceConfigSpec cdSpec = null;

            if (ideCtlr != null)
            {
                cdSpec = new VirtualDeviceConfigSpec();
                cdSpec.operation = VirtualDeviceConfigSpecOperation.add;
                cdSpec.operationSpecified = true;
                VirtualCdrom cdrom = new VirtualCdrom();
                VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo();
                cdDeviceBacking.datastore = datastoreRef;
                cdDeviceBacking.fileName = datastoreVolume + "testcd.iso";
                cdrom.backing = cdDeviceBacking;
                cdrom.key = 20;
                cdrom.controllerKey = ideCtlr.key;
                cdrom.controllerKeySpecified = true;
                cdrom.unitNumberSpecified = true;
                cdrom.unitNumber = 0;
                cdSpec.device = cdrom;
            }

            // Create a new disk - file based - for the vm
            VirtualDeviceConfigSpec diskSpec = null;
            diskSpec = createVirtualDisk(datastoreName, diskCtlrKey, datastoreRef, diskSizeMB);

            // Add a NIC. the network Name must be set as the device name to create the NIC.
            VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
            if (networkName != null)
            {
                nicSpec.operation = VirtualDeviceConfigSpecOperation.add;
                nicSpec.operationSpecified = true;
                VirtualEthernetCard nic = new VirtualPCNet32();
                VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
                nicBacking.deviceName = networkName;
                nic.addressType = "generated";
                nic.backing = nicBacking;
                nic.key = 4;
                nicSpec.device = nic;
            }

            var deviceConfigSpec = new List<VirtualDeviceConfigSpec>();
            deviceConfigSpec.Add(scsiCtrlSpec);
            deviceConfigSpec.Add(floppySpec);
            deviceConfigSpec.Add(diskSpec);
            deviceConfigSpec.Add(nicSpec);

            if (ideCtlr != null)
            {
                deviceConfigSpec.Add(cdSpec);
            }

            configSpec.deviceChange = deviceConfigSpec.ToArray();
            return configSpec;
        }
Esempio n. 30
0
        /// <summary>
        /// Reconfig the virtual machine.
        /// </summary>
        private void reconfigVirtualMachine() {
           Console.WriteLine("ReConfigure The Virtual Machine ..........");
           VirtualMachineFileInfo vmFileInfo 
              = new VirtualMachineFileInfo();
           vmFileInfo.logDirectory = "["+getDataStore()+"]"+getVmName();
           vmFileInfo.snapshotDirectory= "["+getDataStore()+"]"+getVmName();
           vmFileInfo.suspendDirectory= "["+getDataStore()+"]"+getVmName();
           vmFileInfo.vmPathName= "["+getDataStore()
                                       +"]"+getVmName()+"/"+getVmName()+".vmx";

           VirtualMachineConfigSpec vmConfigSpec 
              = new VirtualMachineConfigSpec();
           vmConfigSpec.files =vmFileInfo;

           ManagedObjectReference taskmor 
              = _service.ReconfigVM_Task(
                   getVmMor(getVmName()),vmConfigSpec);

           Object[] result = cb.getServiceUtil().WaitForValues(
                 taskmor, new String[] { "info.state", "info.error" }, 
                 new String[] { "state" },
                 new Object[][] { new Object[] { TaskInfoState.success, TaskInfoState.error }}
           );

           if (result[0].Equals(TaskInfoState.success)) {
              Console.WriteLine("ReConfigure The Virtual Machine .......... Done");
           } else {
             Console.WriteLine("Some Exception While Reconfiguring The VM " + result[0]);
           }
         }
        public void DeployAndConnectIso( string localPath, string remotePath )
        {
            UploadArtifact( localPath, remotePath );

            _vm.UpdateViewData();

            VirtualCdrom cd = _vm.Config.Hardware.Device.FirstOrDefault( d => d is VirtualCdrom ) as VirtualCdrom;

            if ( cd == null )
            {
                throw new ApplicationException( "CD is null" );
            }

            VirtualCdromIsoBackingInfo newBacking = new VirtualCdromIsoBackingInfo
                                                        {
                                                            FileName = string.Format( "[{0}] {1}", _vmWareConfiguration.DataStoreName, remotePath )
                                                        };
            cd.Backing = newBacking;
            cd.Connectable.StartConnected = true;
            cd.Connectable.Connected = true;

            VirtualDeviceConfigSpec deviceSpec = new VirtualDeviceConfigSpec
                                                     {
                                                         Device = cd,
                                                         Operation = VirtualDeviceConfigSpecOperation.edit
                                                     };

            VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec
                                                  {
                                                      DeviceChange = new[] {deviceSpec}
                                                  };

            _vm.ReconfigVM( vmSpec );
        }
Esempio n. 32
0
        private void createVM()
        {
            _service = cb.getConnection()._service;
            String dcName = cb.get_option("datacentername");
            ManagedObjectReference dcmor
                = cb.getServiceUtil().GetDecendentMoRef(null, "Datacenter", dcName);

            if (dcmor == null)
            {
                Console.WriteLine("Datacenter " + dcName + " not found.");
                return;
            }
            try
            {
                ManagedObjectReference hfmor
                    = cb.getServiceUtil().GetMoRefProp(dcmor, "hostFolder");
                ArrayList crmors
                    = cb.getServiceUtil().GetDecendentMoRefs(hfmor, "ComputeResource", null);

                String hostName = cb.get_option("hostname");
                ManagedObjectReference hostmor;

                if (hostName != null)
                {
                    hostmor = cb.getServiceUtil().GetDecendentMoRef(hfmor, "HostSystem", hostName);
                    if (hostmor == null)
                    {
                        Console.WriteLine("Host " + hostName + " not found");
                        return;
                    }
                }
                else
                {
                    hostmor = cb.getServiceUtil().GetFirstDecendentMoRef(dcmor, "HostSystem");
                }

                ManagedObjectReference crmor = null;
                hostName = (String)cb.getServiceUtil().GetDynamicProperty(hostmor, "name");
                for (int i = 0; i < crmors.Count; i++)
                {
                    ManagedObjectReference[] hrmors
                        = (ManagedObjectReference[])cb.getServiceUtil().GetDynamicProperty((ManagedObjectReference)crmors[i], "host");
                    if (hrmors != null && hrmors.Length > 0)
                    {
                        for (int j = 0; j < hrmors.Length; j++)
                        {
                            String hname
                                = (String)cb.getServiceUtil().GetDynamicProperty(hrmors[j], "name");
                            if (hname.Equals(hostName))
                            {
                                crmor = (ManagedObjectReference)crmors[i];
                                i     = crmors.Count + 1;
                                j     = hrmors.Length + 1;
                            }
                        }
                    }
                }

                if (crmor == null)
                {
                    Console.WriteLine("No Compute Resource Found On Specified Host");
                    return;
                }

                ManagedObjectReference resourcePool
                    = cb.getServiceUtil().GetMoRefProp(crmor, "resourcePool");
                ManagedObjectReference vmFolderMor
                    = cb.getServiceUtil().GetMoRefProp(dcmor, "vmFolder");

                VirtualMachineConfigSpec vmConfigSpec =
                    vmUtils.createVmConfigSpec(cb.get_option("vmname"),
                                               cb.get_option("datastorename"),
                                               int.Parse(cb.get_option("disksize")),
                                               crmor, hostmor);


                vmConfigSpec.name              = cb.get_option("vmname");
                vmConfigSpec.annotation        = "VirtualMachine Annotation";
                vmConfigSpec.memoryMB          = (long)(int.Parse(cb.get_option("memorysize")));
                vmConfigSpec.memoryMBSpecified = true;
                vmConfigSpec.numCPUs           = int.Parse(cb.get_option("cpucount"));
                vmConfigSpec.numCPUsSpecified  = true;
                vmConfigSpec.guestId           = (cb.get_option("guestosid"));

                ManagedObjectReference taskmor = _service.CreateVM_Task(
                    vmFolderMor, vmConfigSpec, resourcePool, hostmor
                    );
                String res = cb.getServiceUtil().WaitForTask(taskmor);
                if (res.Equals("sucess"))
                {
                    Console.WriteLine("Virtual Machine Created Sucessfully");
                }
                else
                {
                    Console.WriteLine("Virtual Machine could not be created. ");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
        }