Example #1
0
        public void AddDisk(string opaqueref, bool owner, bool isShared)
        {
            VM.VBDs.Add(new XenRef<VBD>(opaqueref));

            _mockConnection.Setup(x => x.Resolve<VDI>(new XenRef<VDI>(opaqueref))).Returns(new VDI()
            {
                opaque_ref = opaqueref,
                Connection = _mockConnection.Object,
                SR = new XenRef<SR>(opaqueref),
                managed = true,
                missing = false
            });
            VBD vbd = new VBD
                          {
                              opaque_ref = opaqueref,
                              VDI = new XenRef<VDI>(opaqueref),
                              other_config = new Dictionary<string, string>(),
                              Connection = _mockConnection.Object,
                              IsOwner = owner
                          };
            _vbds.Add(vbd);
            _mockConnection.Setup(x => x.Resolve<VBD>(new XenRef<VBD>(opaqueref))).Returns(vbd);
            _mockConnection.Setup(x => x.Resolve<SR>(new XenRef<SR>(opaqueref))).Returns(new SR()
            {
                Connection = _mockConnection.Object,
                shared = isShared,
                PBDs = new List<XenRef<PBD>>() { new XenRef<PBD>(opaqueref) }
            });
            _mockConnection.Setup(x => x.Resolve<PBD>(It.IsAny<XenRef<PBD>>())).Returns(new PBD());
        }
Example #2
0
 public VbdEditAction(VBD vbd, vbd_mode vbdMode, int priority, bool changeDevicePosition, VBD other, string devicePosition, bool suppressHistory)
     : base(vbd.Connection, string.Format(Messages.ACTION_SAVE_SETTINGS, vbd.Connection.Resolve(vbd.VDI)), string.Format(Messages.ACTION_SAVE_SETTINGS, vbd.Connection.Resolve(vbd.VDI)), suppressHistory)
 {
     this._vbd = vbd;
     _priority = priority;
     VM = vbd.Connection.Resolve(vbd.VM);
     this._vbdMode = vbdMode;
     this._changeDevicePosition = changeDevicePosition;
     this._other = other;
     this._devicePosition = devicePosition;
 }
Example #3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="vm"></param>
        /// <param name="vdi">May be null, indicating that the CD should be ejected (i.e. set to empty).</param>
        /// <param name="cdrom">Must not be null.</param>
        public ChangeVMISOAction(IXenConnection connection, VM vm,
            VDI vdi, VBD cdrom)
            : base(connection, vdi == null ? String.Format(Messages.ISO_UNLOADING, vm.Name) :
            String.Format(Messages.ISO_LOADING, vdi.Name, vm.Name))
        {
            this.VM = vm;
            this.vdi = vdi;
            this.cdrom = cdrom;

            System.Diagnostics.Trace.Assert(this.cdrom != null, "ChangeVMISOAction ctor: cdrom vbd must not be null");
            System.Diagnostics.Trace.Assert(this.VM != null, "ChangeVMISOAction ctor: VM must not be null");
        }
Example #4
0
        /// <summary>
        /// Arguments should never be null
        /// </summary>
        public VBDRow(VBD vbd, VDI vdi, SR sr)
        {
            Debug.Assert(vbd != null && vdi != null && sr != null, "vbd, vdi and sr must be set to a non-null value");

            VBD = vbd;
            VDI = vdi;
            SR = sr;

            for (int i = 0; i < 10; i++)
            {
                DataGridViewTextBoxCell c = new DataGridViewTextBoxCell();
                c.Value = CellValue(i);
                Cells.Add(c);
            }
        }
Example #5
0
        private bool CanExecute(VBD vbd)
        {
            VDI vdi = vbd.Connection.Resolve<VDI>(vbd.VDI);
            VM vm = vbd.Connection.Resolve<VM>(vbd.VM);
            if (vm == null || vm.not_a_real_vm || vdi == null || vdi.Locked || vbd.Locked)
                return false;
            if (vm.power_state != vm_power_state.Running)
                return false;
            if (vdi.type == vdi_type.system && vbd.IsOwner)
                return false;
            if (!vm.GetVirtualisationStatus.HasFlag(VM.VirtualisationStatus.IO_DRIVERS_INSTALLED))
                return false;
            if (!vbd.currently_attached)
                return false;

            return vbd.allowed_operations.Contains(vbd_operations.unplug);
        }
 /// <summary>
 /// Detaches a virtual disk
 /// </summary>
 /// <param name="disk">The VDI to detach</param>
 /// <param name="vm">The VM to detach it from</param>
 /// <param name="takeVDILock">Whether it is necessary to lock the VDI (we may be part of another disk action)</param>
 public DetachVirtualDiskAction(VDI disk, VM vm, bool takeVDILock)
     : base(disk.Connection, string.Format(Messages.ACTION_DISK_DETACHING_TITLE, disk.Name, vm.Name, false))
 {
     this.takeVDILock = takeVDILock;
     vdi = disk;
     if (takeVDILock)
         vdi.Locked = true;
     VM = vm;
     VM.Locked = true;
     foreach (VBD v in Connection.ResolveAll<VBD>(VM.VBDs))
     {
         if (v.VDI.opaque_ref == vdi.opaque_ref)
         {
             vbd = v;
             vbd.Locked = true;
         }
     }
 }
Example #7
0
 public VbdEditAction(VBD vbd, vbd_mode vbdMode, int priority, bool changeDevicePosition, VBD other, string devicePosition, bool suppressHistory)
     : base(vbd.Connection, string.Format(Messages.ACTION_SAVE_SETTINGS, vbd.Connection.Resolve(vbd.VDI)), string.Format(Messages.ACTION_SAVE_SETTINGS, vbd.Connection.Resolve(vbd.VDI)), suppressHistory)
 {
     this._vbd     = vbd;
     _priority     = priority;
     VM            = vbd.Connection.Resolve(vbd.VM);
     this._vbdMode = vbdMode;
     this._changeDevicePosition = changeDevicePosition;
     this._other          = other;
     this._devicePosition = devicePosition;
 }
Example #8
0
        /// <summary>
        /// Deactivates a single VBD
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <param name="vbd"></param>
        public DeactivateVBDCommand(IMainWindow mainWindow, VBD vbd)
            : base(mainWindow, vbd)
        {

        }
Example #9
0
        private static void DestroyVM(Session session, VM vm, List <VBD> deleteDisks, IEnumerable <VM> deleteSnapshots)
        {
            var caught = new List <Exception>();

            foreach (VM snapshot in deleteSnapshots)
            {
                VM snap = snapshot;
                try
                {
                    if (snap.power_state == vm_power_state.Suspended)
                    {
                        VM.hard_shutdown(session, snap.opaque_ref);
                    }
                    DestroyVM(session, snap, true);
                }
                catch (Exception e)
                {
                    log.Error($"Failed to delete snapshot {snap.opaque_ref}", e);
                    caught.Add(e);
                }
            }

            List <XenRef <VDI> > vdiRefs = new List <XenRef <VDI> >();

            foreach (XenRef <VBD> vbdRef in vm.VBDs)
            {
                VBD vbd = vm.Connection.Resolve(vbdRef);
                if (vbd == null)
                {
                    continue;
                }

                if (deleteDisks.Contains(vbd))
                {
                    if (vbd.Connection.Resolve(vbd.VDI) != null)
                    {
                        vdiRefs.Add(vbd.VDI);
                    }
                }
            }

            //CA-91072: Delete Suspend image VDI
            VDI suspendVDI = vm.Connection.Resolve(vm.suspend_VDI);

            if (suspendVDI != null)
            {
                vdiRefs.Add(vm.suspend_VDI);
            }

            VM.destroy(session, vm.opaque_ref);

            foreach (XenRef <VDI> vdiRef in vdiRefs)
            {
                try
                {
                    VDI.destroy(session, vdiRef.opaque_ref);
                }
                catch (Exception e)
                {
                    //CA-115249. XenAPI could have already deleted the VDI.
                    //Destroy suspended VM and destroy snapshot functions are affected.

                    if (e is Failure failure && failure.ErrorDescription != null &&
                        failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == "HANDLE_INVALID")
                    {
                        log.InfoFormat($"VDI {vdiRef.opaque_ref} has already been deleted; ignoring API failure.");
                    }
Example #10
0
 public DiskDescription(VDI disk, VBD device)
 {
     Disk = disk;
     Device = device;
     Type = DiskType.New;
 }
Example #11
0
        private bool DiskOk(DiskDescription disk, VBD vbd)
        {
            if (vbd == null)
                return false;

            VDI vdi = Connection.Resolve(vbd.VDI);

            return vdi != null && disk.Disk.SR.opaque_ref == vdi.SR.opaque_ref;
        }
Example #12
0
        private VBD CreateCdDrive()
        {
            List<string> devices = AllowedVBDs;
            if (devices.Count == 0)
                throw new Exception(Messages.NO_MORE_USERDEVICES);
            VBD vbd = new VBD();
            vbd.bootable = InsMethod == InstallMethod.CD;
            vbd.empty = true;
            vbd.unpluggable = true;
            vbd.mode = vbd_mode.RO;
            vbd.type = vbd_type.CD;
            vbd.userdevice = devices.Contains("3") ? "3" : devices[0];
            vbd.device = "";
            vbd.VM = new XenRef<VM>(VM.opaque_ref);
            vbd.VDI = null;
            RelatedTask = VBD.async_create(Session, vbd);
            PollToCompletion(60, 65);

            return Connection.WaitForCache(new XenRef<VBD>(Result));
        }
Example #13
0
        protected override void TestCore()
        {
            // Choose a linux VM at random which is not a template or control domain and which is currently switched off.

            var vmRecords = VM.get_all_records(_session);

            var vmRef = (from KeyValuePair <XenRef <VM>, VM> kvp in vmRecords
                         let theVm = kvp.Value
                                     where !theVm.is_a_template && !theVm.is_control_domain &&
                                     !theVm.name_label.ToLower().Contains("windows") &&
                                     theVm.power_state == vm_power_state.Halted
                                     select kvp.Key).FirstOrDefault();

            if (vmRef == null)
            {
                var msg = "Cannot find a halted linux VM. Please create one.";
                _logger.Log(msg);
                throw new Exception(msg);
            }

            //to avoid playing with existing data, clone the VM and powercycle its clone

            VM vm = VM.get_record(_session, vmRef);

            _logger.Log("Cloning VM '{0}'...", vm.name_label);
            string cloneVmRef = VM.clone(_session, vmRef, string.Format("Cloned VM (from '{0}')", vm.name_label));

            _logger.Log("Cloned VM; new VM's ref is {0}", cloneVmRef);

            VM.set_name_description(_session, cloneVmRef, "Another cloned VM");
            VM cloneVm = VM.get_record(_session, cloneVmRef);

            _logger.Log("Clone VM's Name: {0}, Description: {1}, Power State: {2}", cloneVm.name_label,
                        cloneVm.name_description, cloneVm.power_state);

            _logger.Log("Starting VM in paused state...");
            VM.start(_session, cloneVmRef, true, true);
            _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef));

            _logger.Log("Unpausing VM...");
            VM.unpause(_session, cloneVmRef);
            _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef));

            // here we need to delay for a bit until the suspend feauture is written
            // in the guest metrics; this check should be enough for most guests;
            // let's try a certain number of times with 5sec sleeps inbetween
            int max = 5;

            for (int i = 0; i < max; i++)
            {
                cloneVm = VM.get_record(_session, cloneVmRef);
                var metrics = VM_guest_metrics.get_record(_session, cloneVm.guest_metrics);
                if (metrics.other.ContainsKey("feature-suspend") && metrics.other["feature-suspend"] == "1")
                {
                    break;
                }
                _logger.Log("Checked for feature-suspend count {0} out of {1}; will re-try in 5sec.", i + 1, max);
                Thread.Sleep(5000);
            }

            _logger.Log("Suspending VM...");
            VM.suspend(_session, cloneVmRef);
            _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef));

            _logger.Log("Resuming VM...");
            VM.resume(_session, cloneVmRef, false, true);
            _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef));

            _logger.Log("Forcing shutdown VM...");
            VM.hard_shutdown(_session, cloneVmRef);
            _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef));

            cloneVm = VM.get_record(_session, cloneVmRef);
            var vdis = (from vbd in cloneVm.VBDs
                        let vdi = VBD.get_VDI(_session, vbd)
                                  where vdi.opaque_ref != "OpaqueRef:NULL"
                                  select vdi).ToList();

            _logger.Log("Destroying VM...");
            VM.destroy(_session, cloneVmRef);

            _logger.Log("Destroying VM's disks...");
            foreach (var vdi in vdis)
            {
                VDI.destroy(_session, vdi);
            }

            _logger.Log("VM destroyed.");
        }
Example #14
0
        private AsyncAction getActivateVBDAction(VBD vbd)
        {
            VDI    vdi       = vbd.Connection.Resolve <VDI>(vbd.VDI);
            VM     vm        = vbd.Connection.Resolve <VM>(vbd.VM);
            String title     = String.Format(Messages.ACTION_DISK_ACTIVATING_TITLE, vdi.Name(), vm.Name());
            String startDesc = Messages.ACTION_DISK_ACTIVATING;
            String endDesc   = Messages.ACTION_DISK_ACTIVATED;

            AsyncAction action = new DelegatedAsyncAction(vbd.Connection,
                                                          title, startDesc, endDesc, session => VBD.plug(session, vbd.opaque_ref), "vbd.plug");

            action.VM = vm;
            return(action);
        }
Example #15
0
        protected override string GetCantExecuteReasonCore(IXenObject item)
        {
            VBD vbd = item as VBD;

            if (vbd == null)
            {
                return(base.GetCantExecuteReasonCore(item));
            }

            VM  vm  = vbd.Connection.Resolve <VM>(vbd.VM);
            VDI vdi = vbd.Connection.Resolve <VDI>(vbd.VDI);

            if (vm == null || vdi == null)
            {
                return(base.GetCantExecuteReasonCore(item));
            }

            if (vm.is_a_template)
            {
                return(Messages.CANNOT_ACTIVATE_TEMPLATE_DISK);
            }

            if (!vm.is_a_real_vm())
            {
                return(base.GetCantExecuteReasonCore(item));
            }

            SR sr = vdi.Connection.Resolve <SR>(vdi.SR);

            if (sr == null)
            {
                return(Messages.SR_COULD_NOT_BE_CONTACTED);
            }

            if (vdi.Locked)
            {
                var vdiType = vdi.VDIType();
                return(vdiType == VDI.FriendlyType.SNAPSHOT
                    ? Messages.CANNOT_ACTIVATE_SNAPSHOT_IN_USE
                    : vdiType == VDI.FriendlyType.ISO
                        ? Messages.CANNOT_ACTIVATE_ISO_IN_USE
                        : Messages.CANNOT_ACTIVATE_VD_IN_USE);
            }

            if (vm.power_state != vm_power_state.Running)
            {
                return(string.Format(
                           Messages.CANNOT_ACTIVATE_VD_VM_HALTED,
                           Helpers.GetName(vm).Ellipsise(50)));
            }

            if (vdi.type == vdi_type.system)
            {
                return(Messages.TOOLTIP_DEACTIVATE_SYSVDI);
            }

            if (AreIODriversNeededAndMissing(vm))
            {
                return(string.Format(
                           vm.HasNewVirtualisationStates() ? Messages.CANNOT_ACTIVATE_VD_VM_NEEDS_IO_DRIVERS : Messages.CANNOT_ACTIVATE_VD_VM_NEEDS_TOOLS,
                           Helpers.GetName(vm).Ellipsise(50)));
            }

            if (vbd.currently_attached)
            {
                return(string.Format(Messages.CANNOT_ACTIVATE_VD_ALREADY_ACTIVE, Helpers.GetName(vm).Ellipsise(50)));
            }

            return(base.GetCantExecuteReasonCore(item));
        }
Example #16
0
 public static Icons GetIconFor(VBD vbd)
 {
     return(Icons.VDI);
 }
Example #17
0
        public static Icons GetIconFor(IXenObject o)
        {
            VM vm = o as VM;

            if (vm != null)
            {
                return(GetIconFor(vm));
            }

            VM_appliance appl = o as VM_appliance;

            if (appl != null)
            {
                return(GetIconFor(appl));
            }

            SR sr = o as SR;

            if (sr != null)
            {
                return(GetIconFor(sr));
            }

            Host host = o as Host;

            if (host != null)
            {
                return(GetIconFor(host));
            }

            Pool pool = o as Pool;

            if (pool != null)
            {
                return(GetIconFor(pool));
            }

            XenAPI.Network network = o as XenAPI.Network;
            if (network != null)
            {
                return(GetIconFor(network));
            }

            VDI vdi = o as VDI;

            if (vdi != null)
            {
                return(GetIconFor(vdi));
            }

            VBD vbd = o as VBD;

            if (vbd != null)
            {
                return(GetIconFor(vbd));
            }

            Folder folder = o as Folder;

            if (folder != null)
            {
                return(GetIconFor(folder));
            }

            PIF pif = o as PIF;

            if (pif != null)
            {
                return(GetIconFor(pif));
            }

            StorageLinkServer storageLinkServer = o as StorageLinkServer;

            if (storageLinkServer != null)
            {
                return(GetIconFor(storageLinkServer));
            }

            StorageLinkSystem storageLinkSystem = o as StorageLinkSystem;

            if (storageLinkSystem != null)
            {
                return(GetIconFor(storageLinkSystem));
            }

            StorageLinkPool storageLinkPool = o as StorageLinkPool;

            if (storageLinkPool != null)
            {
                return(GetIconFor(storageLinkPool));
            }

            StorageLinkVolume storageLinkVolume = o as StorageLinkVolume;

            if (storageLinkVolume != null)
            {
                return(GetIconFor(storageLinkVolume));
            }

            StorageLinkRepository storageLinkRepository = o as StorageLinkRepository;

            if (storageLinkRepository != null)
            {
                return(GetIconFor(storageLinkRepository));
            }

            DockerContainer dockerContainer = o as DockerContainer;

            if (dockerContainer != null)
            {
                return(GetIconFor(dockerContainer));
            }

            System.Diagnostics.Trace.Assert(false,
                                            "You asked for an icon for a type I don't recognise!");

            return(Icons.XenCenter);
        }
        private void LoadDisks()
        {
            DisksGridView.Rows.Clear();
            var rowList = new List <DataGridViewRow>();

            XmlNode provision = Template.ProvisionXml();

            if (provision != null)
            {
                foreach (XmlNode diskNode in provision.ChildNodes)
                {
                    var device = new VBD
                    {
                        userdevice = diskNode.Attributes["device"].Value,
                        bootable   = diskNode.Attributes["bootable"].Value == "true",
                        mode       = vbd_mode.RW
                    };

                    var diskSize = long.Parse(diskNode.Attributes["size"].Value);
                    SR  srUuid   = Connection.Cache.Find_By_Uuid <SR>(diskNode.Attributes["sr"].Value);
                    SR  sr       = GetBestDiskStorage(Connection, diskSize, Affinity, srUuid, out Image icon, out string tooltip);

                    var disk = new VDI
                    {
                        name_label       = string.Format(Messages.STRING_SPACE_STRING, SelectedName, device.userdevice),
                        name_description = Messages.NEWVMWIZARD_STORAGEPAGE_DISK_DESCRIPTION,
                        virtual_size     = diskSize,
                        type             = (vdi_type)Enum.Parse(typeof(vdi_type), diskNode.Attributes["type"].Value),
                        read_only        = false,
                        SR = new XenRef <SR>(sr != null ? sr.opaque_ref : Helper.NullOpaqueRef)
                    };

                    var row = new DiskGridRowItem(Connection, disk, device, DiskSource.FromDefaultTemplate);
                    row.UpdateStatus(icon, tooltip);
                    rowList.Add(row);
                }
            }
            else
            {
                var vbds = Connection.ResolveAll(Template.VBDs);
                foreach (VBD vbd in vbds)
                {
                    if (vbd.type != vbd_type.Disk)
                    {
                        continue;
                    }

                    VDI vdi = Connection.Resolve(vbd.VDI);
                    if (vdi == null)
                    {
                        continue;
                    }

                    var sourceSr = Connection.Resolve(vdi.SR);

                    var device = new VBD
                    {
                        userdevice = vbd.userdevice,
                        bootable   = vbd.bootable,
                        mode       = vbd.mode
                    };

                    SR sr = GetBestDiskStorage(Connection, vdi.virtual_size, Affinity, Connection.Resolve(vdi.SR),
                                               out Image icon, out string tooltip);

                    var disk = new VDI
                    {
                        name_label       = vdi.name_label,
                        name_description = vdi.name_description,
                        virtual_size     = vdi.virtual_size,
                        type             = vdi.type,
                        read_only        = vdi.read_only,
                        sm_config        = vdi.sm_config,
                        SR = new XenRef <SR>(sr != null ? sr.opaque_ref : Helper.NullOpaqueRef)
                    };

                    var row = new DiskGridRowItem(Connection, disk, device, DiskSource.FromCustomTemplate, sourceSr);
                    row.UpdateStatus(icon, tooltip);
                    rowList.Add(row);
                }
            }

            DisksGridView.Rows.AddRange(rowList.ToArray());
            UpdateStatusForEachDisk(true);
        }
Example #19
0
 public DevicePositionComboBoxItem(string position, VBD vbd = null)
 {
     this.vbd      = vbd;
     this.position = position;
 }
Example #20
0
        protected override void Run()
        {
            this.Description = Messages.ACTION_VM_MOVING;
            try
            {
                var vbds     = Connection.ResolveAll(VM.VBDs);
                int halfstep = (int)(90 / (vbds.Count * 2));
                // move the progress bar above 0, it's more reassuring to see than a blank bar as we copy the first disk
                PercentComplete += 10;
                Exception exn = null;

                foreach (VBD oldVBD in vbds)
                {
                    if (!oldVBD.IsOwner)
                    {
                        continue;
                    }

                    var curVdi = Connection.Resolve(oldVBD.VDI);
                    if (curVdi == null || curVdi.SR.opaque_ref == this.SR.opaque_ref)
                    {
                        continue;
                    }

                    RelatedTask = XenAPI.VDI.async_copy(Session, oldVBD.VDI.opaque_ref, this.SR.opaque_ref);
                    PollToCompletion(PercentComplete, PercentComplete + halfstep);
                    var newVDI = Connection.WaitForCache(new XenRef <VDI>(Result));

                    var newVBD = new VBD
                    {
                        IsOwner      = oldVBD.IsOwner,
                        userdevice   = oldVBD.userdevice,
                        bootable     = oldVBD.bootable,
                        mode         = oldVBD.mode,
                        type         = oldVBD.type,
                        unpluggable  = oldVBD.unpluggable,
                        other_config = oldVBD.other_config,
                        VDI          = new XenRef <VDI>(newVDI.opaque_ref),
                        VM           = new XenRef <VM>(VM.opaque_ref)
                    };

                    VBD vbd = oldVBD;
                    BestEffort(ref exn, () => VDI.destroy(Session, vbd.VDI.opaque_ref));
                    Connection.WaitForCache <VBD>(VBD.create(Session, newVBD));

                    PercentComplete += halfstep;
                }

                if (Helpers.BostonOrGreater(Connection))
                {
                    VM.set_suspend_SR(Session, VM.opaque_ref, SR.opaque_ref);
                }

                if (exn != null)
                {
                    throw exn;
                }
            }
            catch (CancelledException)
            {
                this.Description = string.Format(Messages.MOVE_CANCELLED, VM.Name);
                throw;
            }
            this.Description = Messages.MOVED;
        }
Example #21
0
 /// <summary>
 /// Deactivates a single VBD
 /// </summary>
 /// <param name="mainWindow"></param>
 /// <param name="vbd"></param>
 public ActivateVBDCommand(IMainWindow mainWindow, VBD vbd)
     : base(mainWindow, vbd)
 {
 }
Example #22
0
 public VBD NewDevice()
 {
     VBD vbd = new VBD();
     vbd.Connection = connection;
     vbd.device = "";
     vbd.empty = false;
     vbd.type = XenAPI.vbd_type.Disk;
     vbd.mode = XenAPI.vbd_mode.RW;
     vbd.IsOwner = true;
     vbd.unpluggable = true;
     return vbd;
 }
Example #23
0
        public AsyncAction SaveSettings()
        {
            // Check user has entered valid params
            if (DevicePositionChanged &&
                vdi.type == vdi_type.system)
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.EDIT_SYS_DISK_WARNING,
                                                         Messages.EDIT_SYS_DISK_WARNING_TITLE),
                           ThreeButtonDialog.ButtonYes,
                           ThreeButtonDialog.ButtonNo))
                {
                    dialogResult = dlg.ShowDialog(this);
                }
                if (DialogResult.Yes != dialogResult)
                {
                    return(null);
                }
            }

            bool     diskAccessPriorityEnabled = diskAccessPriorityTrackBar.Enabled;
            int      diskAccessPriority        = diskAccessPriorityTrackBar.Value;
            vbd_mode vbdMode        = modeComboBox.SelectedIndex == 0 ? vbd_mode.RW : vbd_mode.RO;
            string   devicePosition = DevicePosition;

            int priorityToSet = vbd.IONice;

            if (diskAccessPriorityEnabled)
            {
                priorityToSet = diskAccessPriority;
            }


            bool changeDevicePosition = false;
            VBD  other = null;

            if (devicePosition != vbd.userdevice)
            {
                foreach (VBD otherVBD in vm.Connection.ResolveAll(vm.VBDs))
                {
                    if (otherVBD.userdevice != devicePosition ||
                        vbd.opaque_ref == otherVBD.opaque_ref)
                    {
                        continue;
                    }

                    other = otherVBD;
                    break;
                }

                if (other == null)
                {
                    changeDevicePosition = true;
                }
                else
                {
                    // The selected userdevice is already in use. Ask the user what to do about this.
                    DialogResult result = new UserDeviceDialog(devicePosition).ShowDialog(this);

                    changeDevicePosition = result != DialogResult.Cancel;

                    if (result == DialogResult.No || !changeDevicePosition)
                    {
                        other = null;
                    }
                }
            }
            WarnUserSwap(vbd, other);

            return(new VbdEditAction(vbd, vbdMode, priorityToSet, changeDevicePosition, other, devicePosition, true));
        }
Example #24
0
        private bool CanExecute(VBD vbd)
        {
            VM vm = vbd.Connection.Resolve<VM>(vbd.VM);
            VDI vdi = vbd.Connection.Resolve<VDI>(vbd.VDI);
            if (vm == null || vm.not_a_real_vm || vdi == null)
                return false;
            if (vm.power_state != vm_power_state.Running)
                return false;
            if (vdi.type == vdi_type.system)
                return false;
            if (AreIODriversNeededAndMissing(vm))
                return false;
            if (vbd.currently_attached)
                return false;

            return vbd.allowed_operations.Contains(vbd_operations.plug);
        }
        private void AddDisks()
        {
            Description = Messages.CREATING_DISKS;
            List <VBD> vbds = Connection.ResolveAll(VM.VBDs);

            bool   firstDisk = true;
            string suspendSr = null;

            double progress = 70;
            double step     = 20.0 / (double)Disks.Count;

            foreach (DiskDescription disk in Disks)
            {
                VBD vbd = GetDiskVBD(disk, vbds);
                VDI vdi = null;
                if (vbd != null)
                {
                    vdi = Connection.Resolve <VDI>(vbd.VDI);
                }
                if (!DiskOk(disk, vbd))
                {
                    if (vbd != null)
                    {
                        vdi = MoveDisk(disk, vbd, progress, step);
                    }
                    else
                    {
                        vdi = CreateDisk(disk, progress, step);
                    }
                }

                if (vdi == null)
                {
                    continue;
                }

                if (vdi.name_description != disk.Disk.name_description)
                {
                    VDI.set_name_description(Session, vdi.opaque_ref, disk.Disk.name_description);
                }
                if (vdi.name_label != disk.Disk.name_label)
                {
                    VDI.set_name_label(Session, vdi.opaque_ref, disk.Disk.name_label);
                }

                if (firstDisk && Helpers.BostonOrGreater(Connection))
                {
                    //use the first disk to set the VM.suspend_SR
                    SR vdiSR = Connection.Resolve(vdi.SR);
                    this.firstSR = vdiSR;
                    if (vdiSR != null && !vdiSR.HBALunPerVDI)
                    {
                        suspendSr = vdi.SR;
                    }
                    firstDisk = false;
                }

                progress += step;
            }
            if (Helpers.BostonOrGreater(Connection))
            {
                VM.set_suspend_SR(Session, VM.opaque_ref, suspendSr);
            }
        }
Example #26
0
 /// <summary>
 /// Create a VBD
 /// 
 /// ** vbd.bootable **
 /// 1. Windows ignores bootable flag
 /// 2. Eliloader changes the device "0" to bootable when booting linux
 /// </summary>
 /// <param name="disk"></param>
 /// <param name="vdi"></param>
 /// <param name="progress1"></param>
 /// <param name="progress2"></param>
 /// <param name="bootable">Set VBD.bootable to this value - see comments above</param>
 private void CreateVbd(DiskDescription disk, VDI vdi, double progress1, double progress2, bool bootable)
 {
     List<string> devices = AllowedVBDs;
     if (devices.Count == 0)
         throw new Exception(Messages.NO_MORE_USERDEVICES);
     VBD vbd = new VBD();
     vbd.IsOwner = true;
     vbd.bootable = bootable;
     vbd.empty = false;
     vbd.unpluggable = true;
     vbd.mode = vbd_mode.RW;
     vbd.type = vbd_type.Disk;
     vbd.userdevice = devices.Contains(disk.Device.userdevice) ? disk.Device.userdevice : devices[0];
     vbd.device = "";
     vbd.VM = new XenRef<VM>(VM.opaque_ref);
     vbd.VDI = new XenRef<VDI>(vdi.opaque_ref);
     RelatedTask = VBD.async_create(Session, vbd);
     PollToCompletion(progress1, progress2);
     Connection.WaitForCache(new XenRef<VBD>(Result));
 }
Example #27
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="vm"></param>
        /// <param name="vbd"></param>
        /// <param name="userdevice"></param>
        /// <param name="plug"></param>
        /// <returns>True if it warned the user, so you don't warn twice</returns>
        private static void SetUserDevice(Session session, VM vm, VBD vbd, String userdevice, bool plug)
        {
            //Program.AssertOffEventThread();

            if (vm.power_state == vm_power_state.Running &&
                vbd.currently_attached &&
                vbd.allowed_operations.Contains(vbd_operations.unplug))
            {
                VBD.unplug(session, vbd.opaque_ref);
            }

            VBD.set_userdevice(session, vbd.opaque_ref, userdevice);

            if (plug && vbd.allowed_operations.Contains(vbd_operations.plug) && vm.power_state == vm_power_state.Running)
            {
                VBD.plug(session, vbd.opaque_ref);
            }
        }
Example #28
0
        private VDI MoveDisk(DiskDescription disk, VBD vbd, double progress, double step)
        {
            string old_vdi_ref = vbd.VDI.opaque_ref;

            RelatedTask = XenAPI.VDI.async_copy(Session, vbd.VDI.opaque_ref, disk.Disk.SR.opaque_ref);
            PollToCompletion(progress, progress + 0.25 * step);
            AddVMHint(Connection.WaitForCache(new XenRef<VDI>(Result)));

            VDI new_vdi = Connection.Resolve(new XenRef<VDI>(Result));

            RelatedTask = XenAPI.VBD.async_destroy(Session, vbd.opaque_ref);
            PollToCompletion(progress + 0.25 * step, progress + 0.5 * step);

            RelatedTask = XenAPI.VDI.async_destroy(Session, old_vdi_ref);
            PollToCompletion(progress + 0.5 * step, progress + 0.75 * step);

            CreateVbd(disk, new_vdi, progress + 0.75 * step, progress + step, IsDeviceAtPositionZero(disk));
            return new_vdi;
        }
Example #29
0
        private void AddResourceSettingData(Session xenSession, XenRef<VM> vmRef, RASD_Type rasd, string pathToOvf, string filename, string compression, string version, string passcode)
        {
            switch (rasd.ResourceType.Value)
            {
                case 3: // Processor: Already set in DefineSystem
                case 4: // Memory: Already set in DefineSystem
                case 5: // Internal Disk Controller of one type or another.
                case 6:
                case 7:
                case 8:
                case 9:
                    {
                        // For Xen really nothing to do here, does not support the different
                        // controller types, therefore we must ensure
                        // via positional on controllers.
                        // IDE - #1
                        // SCSI - #2
                        // IDE 0 Disk  0 Goes to Xen: userdevice=0
                        // IDE 0 Disk  1 Goes to Xen: userdevice=1
                        // IDE 1 Disk  0 Goes to Xen: userdevice=2
                        // IDE 1 CDDVD 1 Goes to Xen: userdevice=3
                        // SCSI 0 Disk 0 Goes to Xen: userdevice=4
                        // SCSI 0 Disk 1 Goes to Xen: userdevice=5
                        // and so forth.
                        break;
                    }
                case 10: // Network
                    {
                        XenRef<Network> net = null;
                        XenRef<Network> netDefault = null;
                        string netuuid = null;

                        #region SELECT NETWORK
                        Dictionary<XenRef<Network>, Network> networks = Network.get_all_records(xenSession);
                        if (rasd.Connection != null && rasd.Connection.Length > 0)
                        {
                            if (!string.IsNullOrEmpty(rasd.Connection[0].Value))
                            {
                                // Ignore the NetworkSection/Network
                                // During Network Selection the UUID for Network was set in Connection Field
                                // Makes data self contained here.

                                if (rasd.Connection[0].Value.Contains(Properties.Settings.Default.xenNetworkKey) ||
                                    rasd.Connection[0].Value.Contains(Properties.Settings.Default.xenNetworkUuidKey))
                                {
                                    string[] s = rasd.Connection[0].Value.Split(new char[] { ',' });
                                    for (int i = 0; i < s.Length; i++)
                                    {
                                        if (s[i].StartsWith(Properties.Settings.Default.xenNetworkKey) ||
                                            s[i].StartsWith(Properties.Settings.Default.xenNetworkUuidKey))
                                        {
                                            string[] s1 = s[i].Split(new char[] { '=' } );
                                            netuuid = s1[1];
                                        }
                                    }
                                }
                                foreach (XenRef<Network> netRef in networks.Keys)
                                {
                                    // if its a UUID and we find it... use it..
                                    if (net == null && netuuid != null &&
                                        netuuid.Equals(networks[netRef].uuid))
                                    {
                                        net = netRef;
                                    }
                                    // Ok second is to match it as a NAME_LABEL
                                    else if (net == null && netuuid != null &&
                                        networks[netRef].name_label.ToLower().Contains(netuuid))
                                    {
                                        net = netRef;
                                    }
                                    // hhmm neither... is it a BRIDGE name?
                                    else if (net == null && netuuid != null &&
                                        networks[netRef].bridge.ToLower().Contains(netuuid))
                                    {
                                        net = netRef;
                                    }
                                    // ok find the default.
                                    if (networks[netRef].bridge.ToLower().Contains(Properties.Settings.Default.xenDefaultNetwork))
                                    {
                                        netDefault = netRef;
                                    }
                                }
                                if (net == null)
                                {
                                    net = netDefault;
                                }
                            }
                        }
                        #endregion

                        #region ATTACH NETWORK TO VM
                        Hashtable vifHash = new Hashtable();
                        // This is MAC address if available use it.
                        // needs to be in form:  00:00:00:00:00:00
                        if (Tools.ValidateProperty("Address", rasd))
                        {
                            StringBuilder networkAddress = new StringBuilder();
                            if (!rasd.Address.Value.Contains(":"))
                            {
                                for (int i = 0; i < rasd.Address.Value.Length; i++)
                                {
                                    if ((i > 0) && (i % 2) == 0)
                                    {
                                        networkAddress.Append(":");
                                    }
                                    networkAddress.Append(rasd.Address.Value[i]);
                                }
                            }
                            if (networkAddress.Length == 0)
                            {
                                networkAddress.Append(rasd.Address.Value);
                            }
                            vifHash.Add("MAC", networkAddress.ToString());
                        }
                        vifHash.Add("uuid", Guid.NewGuid().ToString());
                        vifHash.Add("allowed_operations", new string[] { "attach" });
                        vifHash.Add("device", Convert.ToString(vifDeviceIndex++));
                        vifHash.Add("network", net.opaque_ref);
                        vifHash.Add("VM", vmRef.opaque_ref);
                        vifHash.Add("MTU", "1500");
                        vifHash.Add("locking_mode", "network_default");
                        VIF vif = new VIF(vifHash);
                        try
                        {
                            VIF.create(xenSession, vif);
                        }
                        catch (Exception ex)
                        {
                            log.ErrorFormat("{0} {1}", Messages.ERROR_CREATE_VIF_FAILED, ex.Message);
                            throw new Exception(Messages.ERROR_CREATE_VIF_FAILED, ex);
                        }
                        #endregion
                        log.Debug("OVF.Import.AddResourceSettingData: Network Added");

                        break;
                    }
                case 15: // CD Drive
                case 16: // DVD Drive
                    {
                        // We always attach as "EMPTY".
                        // Currenlty Xen Server can only have ONE CD, so we must
                        // Skip the others.
                        // If it's not necessary.. skip it.

                        #region Attach DVD to VM
                        bool SkipCD = false;
                        List<XenRef<VBD>> vbds = VM.get_VBDs(xenSession, vmRef);
                        foreach (XenRef<VBD> vbd in vbds)
                        {
                            vbd_type vbdType = VBD.get_type(xenSession, vbd);
                            if (vbdType == vbd_type.CD)
                            {
                                SkipCD = true;
                                break;
                            }
                        }

                        if (!SkipCD)
                        {
                            List<XenRef<VDI>> vdiRef = new List<XenRef<VDI>>();
                            if (filename != null)
                            {
                                #region IS THE ISO SR IN THE OVF?
                                string isoUuid = null;
                                if (rasd.Connection != null && rasd.Connection.Length > 0)
                                {
                                    if (rasd.Connection[0].Value.ToLower().Contains("sr="))
                                    {
                                        string[] vpairs = rasd.Connection[0].Value.Split(new char[] { ',' });
                                        foreach (string vset in vpairs)
                                        {
                                            if (vset.ToLower().StartsWith("sr="))
                                            {
                                                isoUuid = vset.Substring(vset.LastIndexOf('=') + 1);
                                                try
                                                {
                                                    #region TRY IT AS UUID
                                                    try
                                                    {
                                                        XenRef<SR> srref = SR.get_by_uuid(xenSession, isoUuid);
                                                        if (srref == null)
                                                        {
                                                            isoUuid = null;
                                                        }
                                                        else
                                                        {
                                                            break;
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        traceLog.Debug("Import.AddResourceSettingData: iso sr uuid not found, trying name_label");
                                                    }
                                                    #endregion

                                                    #region TRY IT AS NAME_LABEL
                                                    try
                                                    {
                                                        List<XenRef<SR>> srrefList = SR.get_by_name_label(xenSession, isoUuid);
                                                        if (srrefList != null && srrefList.Count > 0)
                                                        {
                                                            isoUuid = SR.get_uuid(xenSession, srrefList[0]);
                                                            break;
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        traceLog.Debug("Import.AddResourceSettingData: iso sr uuid not found, looking for vdi...");
                                                    }
                                                    #endregion
                                                }
                                                catch (Exception ex)
                                                {
                                                    log.WarnFormat("Import.AddResourceSettingData: could not find SR: {0}", ex.Message);
                                                    isoUuid = null;
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                                #endregion

                                // VDI trumps SR
                                List<XenRef<VDI>> isoVDIlist = VDI.get_by_name_label(xenSession, filename);
                                if (isoVDIlist.Count > 0)
                                {
                                    vdiRef.Add(isoVDIlist[0]);
                                }
                                else
                                {
                                    #region LAST CHANCE USE XENTOOLS ISO SR
                                    if (isoUuid == null)
                                    {
                                        Dictionary<XenRef<SR>, SR> srDictionary = SR.get_all_records(xenSession);
                                        foreach (XenRef<SR> key in srDictionary.Keys)
                                        {
                                            if (srDictionary[key].content_type.ToLower() == "iso" && srDictionary[key].type.ToLower() == "iso")
                                            {
                                                if (srDictionary[key].name_label.ToLower().Equals(Properties.Settings.Default.xenTools.ToLower()))
                                                {
                                                    isoUuid = srDictionary[key].uuid;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    #endregion

                                    #region DO IMPORT ISO FILE
                                    if (isoUuid != null && !MetaDataOnly)
                                    {
                                        _currentfilename = filename;
                                        try
                                        {
                                            vdiRef = ImportFileProc(new TaskInfo(xenSession, this, filename, pathToOvf, filename, isoUuid, version, passcode, compression, "", null));
                                        }
                                        catch (Exception ex)
                                        {
                                            if (ex is OperationCanceledException)
                                                throw;
                                            var msg = string.Format(Messages.ERROR_ADDRESOURCESETTINGDATA_FAILED, Messages.ISO);
                                            log.ErrorFormat("{0}, {1}", msg, ex.Message);
                                            throw new Exception(msg, ex);
                                        }
                                        finally
                                        {
                                            if (vdiRef == null || vdiRef.Count <= 0)
                                            {
                                                log.Error(string.Format(Messages.ERROR_IMPORT_DISK_FAILED, filename, isoUuid));
                                                RemoveSystem(xenSession, vmRef);
                                            }
                                        }
                                    }
                                    #endregion
                                }
                            }
                            else
                            {
                                vdiRef.Add(XenRef<VDI>.Create(string.Empty));
                            }

                            #region CREATE VBD CONNECTION
                            string booleans = "empty,bootable,unpluggable,attachable,storage-lock";
                            string skipvalues = "sr,vdi";

                            foreach (XenRef<VDI> currentVDI in vdiRef)
                            {
                                Hashtable vbdHash = new Hashtable();

                                if (rasd.Connection != null && rasd.Connection.Length > 0)
                                {
                                    string[] valuepairs = rasd.Connection[0].Value.Split(new char[] { ',' });

                                    foreach (string valuepair in valuepairs)
                                    {
                                        string[] namevalue = valuepair.Split(new char[] { '=' });
                                        if (!skipvalues.ToLower().Contains(namevalue[0].ToLower()))
                                        {
                                            string name = namevalue[0];
                                            if (name.ToLower().Equals("device"))
                                            {
                                                name = "userdevice";
                                            }
                                            if (booleans.Contains(name))
                                            {
                                                vbdHash.Add(name, Convert.ToBoolean(namevalue[1]));
                                            }
                                            else
                                            {
                                                vbdHash.Add(name, namevalue[1]);
                                            }
                                        }
                                    }
                                }
                                if (!vbdHash.ContainsKey("vm-name-label")) vbdHash.Add("vm-name-label", VM.get_name_label(xenSession, vmRef));
                                if (!vbdHash.ContainsKey("VM")) vbdHash.Add("VM", vmRef.opaque_ref);
                                if (currentVDI != null && !string.IsNullOrEmpty(currentVDI.opaque_ref))
                                {
                                    // Override values.
                                    if (!vbdHash.ContainsKey("VDI")) vbdHash.Add("VDI", currentVDI.opaque_ref);
                                    else vbdHash["VDI"] = currentVDI.opaque_ref;
                                    if (!vbdHash.ContainsKey("empty")) vbdHash.Add("empty", false);
                                    else vbdHash["empty"] = false;
                                    if (!vbdHash.ContainsKey("bootable")) vbdHash.Add("bootable", true);
                                    else vbdHash["bootable"] = true;
                                    if (!vbdHash.ContainsKey("unpluggable")) vbdHash.Add("unpluggable", true);
                                    else vbdHash["unpluggable"] = true;
                                }
                                else
                                {
                                    // Override.
                                    if (!vbdHash.ContainsKey("empty")) vbdHash.Add("empty", true);
                                    else vbdHash["empty"] = true;
                                }
                                if (!vbdHash.ContainsKey("mode")) vbdHash.Add("mode", "RO");
                                if (!vbdHash.ContainsKey("userdevice")) vbdHash.Add("userdevice", "3");
                                if (!vbdHash.ContainsKey("type")) vbdHash.Add("type", "CD");
                                if (!vbdHash.ContainsKey("attachable")) vbdHash.Add("attachable", true);
                                if (!vbdHash.ContainsKey("storage-lock")) vbdHash.Add("storage-lock", false);
                                if (!vbdHash.ContainsKey("status-code")) vbdHash.Add("status-code", "0");

                                vbdHash["userdevice"] = VerifyUserDevice(xenSession, vmRef, (string)vbdHash["userdevice"]);

                                Hashtable hOtherConfig = new Hashtable();
                                hOtherConfig.Add("owner", "true");
                                vbdHash.Add("other_config", hOtherConfig);

                                if (!((string)vbdHash["userdevice"]).EndsWith("+"))
                                {
                                    VBD vbd = new VBD(vbdHash);
                                    try
                                    {
                                        VBD.create(xenSession, vbd);
                                    }
                                    catch (Exception ex)
                                    {
                                        log.ErrorFormat("Import.AddResourceSettingData: {0}", ex.Message);
                                    }
                                }
                                else
                                {
                                    log.WarnFormat("Import:  ================== ATTENTION NEEDED =======================");
                                    log.WarnFormat("Import:  Could not determine appropriate number of device placement.");
                                    log.WarnFormat("Import:  Please Start, Logon, Shut down, System ({0})", (string)vbdHash["vm_name_label"]);
                                    log.WarnFormat("Import:  Then attach disks with labels ending with \"+\" to the device number defined before the +.");
                                    log.Warn("Import:  ===========================================================");
                                    OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.Progress, "Import", Messages.WARNING_ADMIN_REQUIRED));
                                }
                            }
                            #endregion

                        }
                        #endregion
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ImportProgress, "CD/DVD Drive",
                            string.Format(Messages.DEVICE_ATTACHED, Messages.CD_DVD_DEVICE)));
                        log.Debug("Import.AddResourceSettingData: CD/DVD ROM Added");

                        break;
                    }
                case 17: // Disk Drive
                case 19: // Storage Extent
                case 21: // Microsoft: Harddisk/Floppy/ISO
                    {
                        #region ADD DISK
                        if (filename == null) // NO disk is available, why import RASD?
                        {
                            log.WarnFormat("No file available to import, skipping: RASD{0}: {1}", rasd.ResourceType.Value, rasd.InstanceID.Value);
                            break;
                        }
                        string sruuid = null;
                        string vdiuuid = null;
                        string userdeviceid = null;
                        string namelabel = VM.get_name_label(xenSession, vmRef);
                        bool isbootable = false;
                        string mode = "RW";

                        bool importThisRasd = true;
                        if (Tools.ValidateProperty("Caption", rasd)) // rasd.Caption != null && rasd.Caption.Value != null && rasd.Caption.Value.Length > 0)
                        {
                            if (
                                rasd.Caption.Value.ToUpper().Contains("COM") ||
                                rasd.Caption.Value.ToUpper().Contains("FLOPPY") ||
                                rasd.Caption.Value.ToUpper().Contains("ISO")
                                )
                            {
                                importThisRasd = false;
                            }
                        }

                        if (importThisRasd)
                        {
                            #region IMPORT DISKS
                            if (!MetaDataOnly)
                            {
                                _currentfilename = filename;

                                List<XenRef<VDI>> vdiRef = null;

                                #region PARSE CONNECTION
                                if (Tools.ValidateProperty("Connection", rasd))
                                {
                                    string[] s = rasd.Connection[0].Value.Split(new char[] { '=', ',' });
                                    for (int i = 0; i < s.Length; i++)
                                    {
                                        string checkme = s[i].ToLower().Trim();
                                        switch (checkme)
                                        {
                                            case "device":
                                                {
                                                    userdeviceid = s[++i];
                                                    break;
                                                }
                                            case "bootable":
                                                {
                                                    isbootable = Convert.ToBoolean(s[++i]);
                                                    break;
                                                }
                                            case "mode":
                                                {
                                                    if (s[++i].Equals("r"))
                                                    {
                                                        mode = "RO";
                                                    }
                                                    break;
                                                }
                                            case "vdi":
                                                {
                                                    vdiuuid = s[++i];
                                                    break;
                                                }
                                            case "sr":
                                                {
                                                    sruuid = s[++i];
                                                    break;
                                                }
                                        }
                                    }
                                }
                                #endregion

                                #region VERIFY SR UUID
                                if (!string.IsNullOrEmpty(sruuid))
                                {
                                    XenRef<SR> srref = null;
                                    try
                                    {
                                        srref = SR.get_by_uuid(xenSession, sruuid);
                                    }
                                    catch
                                    {
                                        traceLog.Debug("Import.AddResourceSettingData: SR missing... still looking..");
                                    }
                                    if (srref == null)
                                    {
                                        List<XenRef<SR>> srlist = null;
                                        try
                                        {
                                            srlist = SR.get_by_name_label(xenSession, sruuid);
                                        }
                                        catch
                                        {
                                            traceLog.Debug("Import.AddResourceSettingData: SR missing... still looking..");
                                        }
                                        if (srlist != null && srlist.Count > 0)
                                        {
                                            sruuid = SR.get_uuid(xenSession, srlist[0]);
                                        }
                                    }
                                }
                                else
                                {
                                    sruuid = null;
                                }
                                #endregion

                                #region LAST CHANGE TO FIND SR
                                if (sruuid == null)
                                {
                                    if (DefaultSRUUID == null)
                                    {
                                        log.Error(Messages.ERROR_COULD_NOT_FIND_SR);
                                        throw new InvalidDataException(Messages.ERROR_COULD_NOT_FIND_SR);
                                    }

                                    Dictionary<XenRef<SR>, SR> srDict = SR.get_all_records(xenSession);
                                    if (vdiuuid != null)
                                    {
                                        //Try and get the SR that belongs to the VDI attached
                                        XenRef<VDI> tempVDI = VDI.get_by_uuid(xenSession, vdiuuid);
                                        if (tempVDI == null)
                                        {
                                            log.Error(Messages.ERROR_COULD_NOT_FIND_SR);
                                            throw new InvalidDataException(Messages.ERROR_COULD_NOT_FIND_SR);
                                        }

                                        XenRef<SR> tempSR = VDI.get_SR(xenSession, tempVDI.opaque_ref);
                                        sruuid = srDict[tempSR].uuid;
                                    }
                                    else
                                        sruuid = srDict[DefaultSRUUID].uuid;
                                }
                                #endregion

                                try
                                {
                                    string disklabel = string.Format("{0}_{1}",namelabel, userdeviceid);

                                    if ((rasd.ElementName != null) && (!string.IsNullOrEmpty(rasd.ElementName.Value)))
                                        disklabel = rasd.ElementName.Value;

                                    string description = "";

                                    if ((rasd.Description != null) && (!string.IsNullOrEmpty(rasd.Description.Value)))
                                        description = rasd.Description.Value;

                                    vdiRef = ImportFileProc(new TaskInfo(xenSession, this, disklabel, pathToOvf, filename, sruuid, version, passcode, compression, description, vdiuuid));
                                }
                                catch (Exception ex)
                                {
                                    if (ex is OperationCanceledException)
                                        throw;
                                    var msg = string.Format(Messages.ERROR_ADDRESOURCESETTINGDATA_FAILED, Messages.DISK_DEVICE);
                                    log.ErrorFormat("{0} {1}", msg, ex.Message);
                                    throw new InvalidDataException(msg, ex);
                                }
                                finally
                                {
                                    if (vdiRef == null)
                                    {
                                        var msg = string.Format(Messages.ERROR_IMPORT_DISK_FAILED, filename, sruuid);
                                        log.Error(msg);
                                        RemoveSystem(xenSession, vmRef);
                                    }
                                }

                                log.DebugFormat("Import.AddResourceSettingData coung {0} VDIs", vdiRef.Count);

                                foreach (XenRef<VDI> currentVDI in vdiRef)
                                {
                                    Hashtable vbdHash = new Hashtable();
                                    if (userdeviceid != null)
                                    {
                                        vbdHash.Add("userdevice", VerifyUserDevice(xenSession, vmRef, userdeviceid));
                                    }
                                    else
                                    {
                                        vbdHash.Add("userdevice", VerifyUserDevice(xenSession, vmRef, "99"));
                                    }
                                    vbdHash.Add("bootable", isbootable);
                                    vbdHash.Add("VDI", currentVDI.opaque_ref);
                                    vbdHash.Add("mode", mode);
                                    vbdHash.Add("uuid", Guid.NewGuid().ToString());
                                    vbdHash.Add("vm_name_label", namelabel);
                                    vbdHash.Add("VM", vmRef.opaque_ref);
                                    vbdHash.Add("empty", false);
                                    vbdHash.Add("type", "Disk");
                                    vbdHash.Add("currently_attached", false);
                                    vbdHash.Add("attachable", true);
                                    vbdHash.Add("storage_lock", false);
                                    vbdHash.Add("status_code", "0");

                                    #region SET OTHER_CONFIG STUFF HERE !
                                    //
                                    // below other_config keys XS to delete the disk along with the VM.
                                    //
                                    Hashtable hOtherConfig = new Hashtable();
                                    hOtherConfig.Add("owner", "true");
                                    vbdHash.Add("other_config", hOtherConfig);
                                    #endregion

                                    if (!((string)vbdHash["userdevice"]).EndsWith("+"))
                                    {
                                        VBD vbd = new VBD(vbdHash);

                                        try
                                        {
                                            VBD.create(xenSession, vbd);
                                        }
                                        catch (Exception ex)
                                        {
                                            log.ErrorFormat("{0} {1}", Messages.ERROR_CREATE_VBD_FAILED, ex.Message);
                                            throw new Exception(Messages.ERROR_CREATE_VBD_FAILED, ex);
                                        }
                                    }
                                    else
                                    {
                                        log.WarnFormat("Import:  ================== ATTENTION NEEDED =======================");
                                        log.WarnFormat("Import:  Could not determine appropriate number for device placement.");
                                        log.WarnFormat("Import:  Please Start, Logon, Shut down, System ({0})", (string)vbdHash["vm_name_label"]);
                                        log.WarnFormat("Import:  Then manually attach disks with labels with {0}_# that are not attached to {0}", (string)vbdHash["vm_name_label"]);
                                        log.WarnFormat("Import:  ===========================================================");
                                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.Progress, "Import", Messages.WARNING_ADMIN_REQUIRED));
                                    }
                                }
                            }
                            else
                            {
                                log.InfoFormat("Import: FILE SKIPPED (METADATA ONLY SELECTED)  {0}", _currentfilename);
                            }
                            #endregion

                        }
                        log.Debug("Import.AddResourceSettingData: Hard Disk Image Added");
                        break;
                        #endregion
                    }
            }
        }
Example #30
0
        protected override void Run()
        {
            this.Description = Messages.ACTION_VM_MOVING;
            try
            {
                var vbds = Connection.ResolveAll(VM.VBDs);
                int halfstep = (int)(90/(vbds.Count * 2));
                // move the progress bar above 0, it's more reassuring to see than a blank bar as we copy the first disk
                PercentComplete += 10;
                Exception exn = null;

                foreach (VBD oldVBD in vbds)
                {
                    if (!oldVBD.IsOwner)
                        continue;

                    var curVdi = Connection.Resolve(oldVBD.VDI);
                    if (curVdi == null)
                        continue;

                    if (StorageMapping == null || !StorageMapping.ContainsKey(oldVBD.VDI.opaque_ref))
                        continue;

                    SR sr = StorageMapping[oldVBD.VDI.opaque_ref];
                    if (sr == null || curVdi.SR.opaque_ref == sr.opaque_ref)
                        continue;

                    RelatedTask = XenAPI.VDI.async_copy(Session, oldVBD.VDI.opaque_ref, sr.opaque_ref);
                    PollToCompletion(PercentComplete, PercentComplete + halfstep);
                    var newVDI = Connection.WaitForCache(new XenRef<VDI>(Result));

                    var newVBD = new VBD
                                     {
                                         IsOwner = oldVBD.IsOwner,
                                         userdevice = oldVBD.userdevice,
                                         bootable = oldVBD.bootable,
                                         mode = oldVBD.mode,
                                         type = oldVBD.type,
                                         unpluggable = oldVBD.unpluggable,
                                         other_config = oldVBD.other_config,
                                         VDI = new XenRef<VDI>(newVDI.opaque_ref),
                                         VM = new XenRef<VM>(VM.opaque_ref)
                                     };

                    VBD vbd = oldVBD;
                    BestEffort(ref exn, () => VDI.destroy(Session, vbd.VDI.opaque_ref));
                    Connection.WaitForCache<VBD>(VBD.create(Session, newVBD));

                    PercentComplete += halfstep;
                }

                if (SR != null)
                    VM.set_suspend_SR(Session, VM.opaque_ref, SR.opaque_ref);

                if (exn != null)
                    throw exn;

            }
            catch (CancelledException)
            {
                this.Description = string.Format(Messages.MOVE_CANCELLED, VM.Name);
                throw;
            }
            this.Description = Messages.MOVED;
        }
Example #31
0
        public DiskGridRowItem(IXenConnection connection, XmlNode diskNode, string vmName, Host affinity)
        {
            Disk = new VDI();
            Device = new VBD();
            Connection = connection;

            Disk.virtual_size = long.Parse(diskNode.Attributes["size"].Value);
            SR sruuid = connection.Cache.Find_By_Uuid<SR>(diskNode.Attributes["sr"].Value);
            SR sr = GetBeskDiskStorage(Connection, Disk.virtual_size, affinity, sruuid == null ? null : sruuid);
            Disk.SR = new XenRef<SR>(sr != null ? sr.opaque_ref : Helper.NullOpaqueRef);
            Disk.type = (vdi_type)Enum.Parse(typeof(vdi_type), diskNode.Attributes["type"].Value);
            Device.userdevice = diskNode.Attributes["device"].Value;
            Device.bootable = diskNode.Attributes["bootable"].Value == "true";

            Disk.name_label = string.Format(Messages.NEWVMWIZARD_STORAGEPAGE_VDINAME, vmName, Device.userdevice); //Device.userdevice;
            Disk.read_only = false;
            Disk.name_description = Messages.NEWVMWIZARD_STORAGEPAGE_DISK_DESCRIPTION;
            Device.mode = vbd_mode.RW;

            CanDelete = Disk.type == vdi_type.user;
            CanResize = true;
            MinSize = Disk.virtual_size;

            AddCells();
        }
Example #32
0
        private AsyncAction getDeactivateVBDAction(VBD vbd)
        {
            VDI vdi = vbd.Connection.Resolve<VDI>(vbd.VDI);
            VM vm = vbd.Connection.Resolve<VM>(vbd.VM);
            String title = String.Format(Messages.ACTION_DISK_DEACTIVATING_TITLE, vdi.Name, vm.Name);
            String startDesc = Messages.ACTION_DISK_DEACTIVATING;
            String endDesc = Messages.ACTION_DISK_DEACTIVATED;

            AsyncAction action = new DelegatedAsyncAction(vbd.Connection,
                title, startDesc, endDesc,session => VBD.unplug(session, vbd.opaque_ref), "vbd.unplug");
            action.VM = vm;
            return action;
        }
        protected override void Run()
        {
            Description     = string.Format(Messages.ACTION_MOVING_VDI_STATUS, Helpers.GetName(vdi));
            PercentComplete = 10;
            log.DebugFormat("Moving VDI '{0}'", Helpers.GetName(vdi));
            RelatedTask = VDI.async_copy(Session, vdi.opaque_ref, SR.opaque_ref);
            PollToCompletion(PercentComplete, 60);

            VDI newVdi = Connection.WaitForCache(new XenRef <VDI>(Result));

            // if the original is a suspend VDI, link the suspended VM to the new VDI
            if (vdi.type == vdi_type.suspend)
            {
                var suspendedVm = (from vm in Connection.Cache.VMs
                                   let suspendVdi = Connection.Resolve(vm.suspend_VDI)
                                                    where suspendVdi != null && suspendVdi.uuid == vdi.uuid
                                                    select vm).FirstOrDefault();
                if (suspendedVm != null)
                {
                    VM.set_suspend_VDI(Session, suspendedVm.opaque_ref, newVdi.opaque_ref);
                }
            }
            PercentComplete = 60;

            var newVbds = new List <VBD>();

            foreach (var vbdRef in vdi.VBDs)
            {
                var oldVbd = Connection.Resolve(vbdRef);
                if (oldVbd == null)
                {
                    continue;
                }

                var newVbd = new VBD
                {
                    userdevice   = oldVbd.userdevice,
                    bootable     = oldVbd.bootable,
                    mode         = oldVbd.mode,
                    type         = oldVbd.type,
                    unpluggable  = oldVbd.unpluggable,
                    other_config = oldVbd.other_config,
                    VDI          = new XenRef <VDI>(newVdi.opaque_ref),
                    VM           = new XenRef <VM>(oldVbd.VM)
                };
                newVbd.SetIsOwner(oldVbd.GetIsOwner());
                newVbds.Add(newVbd);

                try
                {
                    if (oldVbd.currently_attached && oldVbd.allowed_operations.Contains(vbd_operations.unplug))
                    {
                        VBD.unplug(Session, vbdRef);
                    }
                }
                finally
                {
                    if (!oldVbd.currently_attached)
                    {
                        VBD.destroy(Session, vbdRef);
                    }
                }
            }

            PercentComplete = 80;

            VDI.destroy(Session, vdi.opaque_ref);

            foreach (var newVbd in newVbds)
            {
                Connection.WaitForCache(VBD.create(Session, newVbd));
            }

            PercentComplete = 100;
            Description     = Messages.COMPLETED;
            log.DebugFormat("Moved VDI '{0}'", Helpers.GetName(vdi));
        }
 public DiskDescription(VDI disk, VBD device)
 {
     Disk   = disk;
     Device = device;
     Type   = DiskType.New;
 }
Example #35
0
        private static void DestroyVM(Session session, VM vm, List <VBD> deleteDisks, IEnumerable <VM> deleteSnapshots)
        {
            Exception caught = null;


            foreach (VM snapshot in deleteSnapshots)
            {
                VM snap = snapshot;
                BestEffort(ref caught, session.Connection.ExpectDisruption, () =>
                {
                    if (snap.power_state == vm_power_state.Suspended)
                    {
                        XenAPI.VM.hard_shutdown(session, snap.opaque_ref);
                    }
                    DestroyVM(session, snap, true);
                });
            }


            List <XenRef <VDI> > vdiRefs = new List <XenRef <VDI> >();

            foreach (XenRef <VBD> vbdRef in vm.VBDs)
            {
                VBD vbd = vm.Connection.Resolve(vbdRef);
                if (vbd == null)
                {
                    continue;
                }


                if (deleteDisks.Contains(vbd))
                {
                    if (vbd.Connection.Resolve(vbd.VDI) != null)
                    {
                        vdiRefs.Add(vbd.VDI);
                    }
                }
            }

            //CA-91072: Delete Suspend image VDI
            VDI suspendVDI = vm.Connection.Resolve(vm.suspend_VDI);

            if (suspendVDI != null)
            {
                vdiRefs.Add(vm.suspend_VDI);
            }

            XenAPI.VM.destroy(session, vm.opaque_ref);


            foreach (XenRef <VDI> vdiRef in vdiRefs)
            {
                XenRef <VDI> vdi = vdiRef;
                BestEffort(ref caught, session.Connection.ExpectDisruption, () => XenAPI.VDI.destroy(session, vdi.opaque_ref));

                //CA-115249. XenAPI could have already deleted the VDI. Destroy suspended VM and destroy snapshot functions are affected.
                var failure = caught as Failure;
                if (failure != null && failure.ErrorDescription != null && failure.ErrorDescription.Count > 0 && failure.ErrorDescription[0] == "HANDLE_INVALID")
                {
                    log.InfoFormat("VDI:{0} has already been deleted -- ignoring exception.", vdi.opaque_ref);
                    caught = null;
                }
            }

            if (caught != null)
            {
                throw caught;
            }
        }
Example #36
0
        private bool CanExecute(VBD vbd)
        {
            VM vm = vbd.Connection.Resolve<VM>(vbd.VM);
            VDI vdi = vbd.Connection.Resolve<VDI>(vbd.VDI);
            if (vm == null || vm.not_a_real_vm || vdi == null)
                return false;
            if (vm.power_state != vm_power_state.Running)
                return false;
            if (vdi.type == vdi_type.system)
                return false;
            if (vm.virtualisation_status != VM.VirtualisationStatus.OPTIMIZED)
                return false;
            if (vbd.currently_attached)
                return false;

            return vbd.allowed_operations.Contains(vbd_operations.plug);
        }
Example #37
0
        private static void WarnUserSwap(VBD vbd, VBD other)
        {
            VM VBDvm = vbd.Connection.Resolve(vbd.VM);
            if ((other != null && VBDvm.power_state != XenAPI.vm_power_state.Halted) &&
                (
                    (vbd.currently_attached && !vbd.allowed_operations.Contains(vbd_operations.unplug))
                    || (other.currently_attached && !other.allowed_operations.Contains(vbd_operations.unplug))

                )
                )
            {
                Program.Invoke(Program.MainWindow, () => new ThreeButtonDialog(
                                                             new ThreeButtonDialog.Details(SystemIcons.Information,
                                                                                           Messages.
                                                                                               DEVICE_POSITION_RESTART_REQUIRED,
                                                                                           Messages.XENCENTER)).
                                                             ShowDialog(Program.MainWindow));
            }
        }
Example #38
0
        public DiskGridRowItem(IXenConnection connection, VDI vdi, VBD vbd, bool isNew, Host affinity)
        {
            SourceDisk = vdi;
            Disk = new VDI();
            Device = new VBD();
            Connection = connection;

            Disk.virtual_size = vdi.virtual_size;
            SR sr = GetBeskDiskStorage(Connection, Disk.virtual_size, affinity, Connection.Resolve(vdi.SR));
            Disk.SR = new XenRef<SR>(sr != null ? sr.opaque_ref : Helper.NullOpaqueRef);
            Disk.type = vdi.type;
            Device.userdevice = vbd.userdevice;
            Device.bootable = vbd.bootable;

            Disk.name_label = vdi.name_label;
            Disk.read_only = vdi.read_only;
            Disk.name_description = vdi.name_description;
            Device.mode = vbd.mode;

            CanDelete = Disk.type == vdi_type.user && isNew;
            CanResize = isNew;
            MinSize = 0;

            AddCells();
        }
Example #39
0
        public void SetXenObjects(IXenObject orig, IXenObject clone)
        {
            if (!(clone is VBD))
                return;

            vbd = clone as VBD;
            if (vbd == null)
                return;

            vdi = vbd.Connection.Resolve(vbd.VDI);
            if (vdi == null)
                return;

            sr = vdi.Connection.Resolve(vdi.SR);
            if (sr == null)
                return;

            Repopulate();

            vm = vbd.Connection.Resolve(vbd.VM);
            if (vm == null)
                return;

            Text = Helpers.GetName(vm);

            devicePositionComboBox.Enabled = false;
        }
Example #40
0
 public static Icons GetIconFor(VBD vbd)
 {
     return Icons.VDI;
 }
Example #41
0
        public object vdicollect(Session session)
        {
            ArrayList    vmc    = new ArrayList();
            string       mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            StreamWriter SW;
            int          vd = 1;

            try
            {
                List <XenRef <VM> >  vmRefs  = VM.get_all(session);
                List <XenRef <VBD> > vbdRefs = VBD.get_all(session);
                List <XenRef <VDI> > vdiRefs = VDI.get_all(session);



                foreach (XenRef <VM> vmRef in vmRefs)
                {
                    VM vm = VM.get_record(session, vmRef);
                    if (!vm.is_a_template && !vm.is_control_domain)
                    {
                        for (int i = 0; i <= vm.VBDs.Count - 1;)
                        {
                            if (vm.VBDs[i].ServerOpaqueRef == "OpaqueRef:NULL")
                            {
                            }
                            else
                            {
                                // get the info from VDB first.
                                VBD vbd = VBD.get_record(session, (String)vm.VBDs[i].ServerOpaqueRef);

                                if (vbd.VDI.ServerOpaqueRef == "OpaqueRef:NULL")
                                {
                                }
                                else
                                {
                                    vmc.Add("Virtual Machine Name:");
                                    try
                                    {
                                        vmc.Add(Convert.ToString(vm.name_label));
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                    VDI vdi = VDI.get_record(session, vbd.VDI.ServerOpaqueRef);
                                    vmc.Add("Virtual Disk Name:");
                                    try
                                    {
                                        vmc.Add(Convert.ToString(vdi.name_label));
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                    vmc.Add("Virtual Description:");
                                    try
                                    {
                                        vmc.Add(Convert.ToString(vdi.name_description));
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                    vmc.Add("Virtual Disk Size:");
                                    try
                                    {
                                        vmc.Add("Not displayed in demo version");
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                    vmc.Add("Physical Disk Usage:");
                                    try
                                    {
                                        vmc.Add("Not displayed in demo version");
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }

                                    SR sr = SR.get_record(session, vdi.SR.ServerOpaqueRef);
                                    vmc.Add("Parent Storage Repositry:");
                                    try
                                    {
                                        vmc.Add(Convert.ToString(sr.name_label));
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }

                                    vmc.Add("Is VDI read-only:");
                                    try
                                    {
                                        vmc.Add(Convert.ToString(vdi.read_only));
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                    vmc.Add("Is VDI Shareable:");
                                    try
                                    {
                                        vmc.Add("Not displayed in demo version");
                                    }
                                    catch
                                    {
                                        vmc.Add("Data not available");
                                        SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                                        SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Error " + vd);
                                        SW.Close();
                                        vd++;
                                    }
                                }

                                i++;
                            }
                        }
                    }
                    vd = 1;
                }
                SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Finished");
                SW.Close();
            }
            catch
            {
                SW = File.AppendText(mydocs + "\\Halfmode\\HalfmodeConnection.log");
                SW.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " VDI Collection Failed");
                SW.Close();
            }
            if ((vmc.Count & 2) == 0)
            {
            }
            else
            {
                vmc.Add(" ");
            }
            return(vmc);
        }