public AssertCanBeRecoveredCheck(IXenObject xenObject, Pool pool, VDI vdi)
     : base(pool)
 {
     this.xenObject = xenObject;
     Vdi            = vdi;
 }
Пример #2
0
        private EnvelopeType _export(Session xenSession, string targetPath, string ovfname, string vmUuid)
        {
            EnvelopeType ovfEnv;

            try
            {
                auditLog.DebugFormat("Export: {0}, {1}", ovfname, targetPath);

                #region GET VM Reference
                XenRef <VM> vmRef = null;

                try
                {
                    vmRef = VM.get_by_uuid(xenSession, vmUuid);
                }
                catch
                {
                    log.WarnFormat("VM not found as uuid: {0}, trying as name-label", vmUuid);
                    vmRef = null;
                }
                if (vmRef == null)
                {
                    try
                    {
                        List <XenRef <VM> > vmRefs = VM.get_by_name_label(xenSession, vmUuid);
                        vmRef = vmRefs[0];
                        traceLog.DebugFormat("{0} VM(s) found by label {1}", vmRefs.Count, vmUuid);
                        if (vmRefs.Count > 1)
                        {
                            log.WarnFormat("Only exporting FIRST VM with name {0}", vmUuid);
                        }
                    }
                    catch
                    {
                        log.ErrorFormat(Messages.ERROR_VM_NOT_FOUND, vmUuid);
                        throw;
                    }
                }
                #endregion

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

                if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended)
                {
                    var message = string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name);
                    OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ExportProgress, "Export", message));
                    log.Info(message);
                    throw new Exception(message);
                }

                #region CREATE ENVELOPE / ADD VIRTUAL SYSTEM
                ovfEnv = OVF.CreateEnvelope(ovfname);
                string vsId  = OVF.AddVirtualSystem(ovfEnv, vm.name_label);
                string vhsId = OVF.AddVirtualHardwareSection(ovfEnv, vsId);
                #endregion

                #region TRY TO ID OS
                XenRef <VM_guest_metrics> vmgmRef = VM.get_guest_metrics(xenSession, vmRef);
                if (!vmgmRef.opaque_ref.ToUpper().Contains("NULL"))
                {
                    VM_guest_metrics vmgm = VM_guest_metrics.get_record(xenSession, vmgmRef);
                    //VM_metrics vmm = VM_metrics.get_record(xenSession, VM.get_metrics(xenSession, vmRef));
                    if (vmgm.os_version != null && vmgm.os_version.Count > 0)
                    {
                        foreach (string key in vmgm.os_version.Keys)
                        {
                            if (key.ToLower().Equals("name"))
                            {
                                ushort osid = ValueMaps.OperatingSystem(vmgm.os_version[key]);
                                if (osid == 0xFFFF)
                                {
                                    osid = 1;
                                }                                 // change to OTHER since search failed.
                                string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO");
                                if (vmgm.os_version.ContainsKey("major") &&
                                    vmgm.os_version.ContainsKey("minor"))
                                {
                                    version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), vmgm.os_version["major"], vmgm.os_version["minor"]);
                                }
                                string osname = (vmgm.os_version[key].Split(new [] { '|' }))[0];
                                OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osname, version, osid);
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region ADD VSSD
                // IS PV'd? for VirtualSystemType identification.
                string typeformat = @"{0}-{1}-{2}";
                string vmtype     = string.Format(typeformat, "hvm", "3.0", "unknown");
                if (vm.HVM_boot_policy != null && vm.HVM_boot_policy == Properties.Settings.Default.xenBootOptions)
                {
                    if (!string.IsNullOrEmpty(vm.domarch))
                    {
                        vmtype = string.Format(typeformat, vm.domarch, "3.0", "unknown");
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(vm.domarch))
                    {
                        vmtype = string.Format(typeformat, "xen", "3.0", vm.domarch);
                    }
                    else
                    {
                        vmtype = string.Format(typeformat, "xen", "3.0", "unknown");
                    }
                }
                OVF.AddVirtualSystemSettingData(ovfEnv, vsId, vhsId, vm.name_label, OVF.GetContentMessage("VSSD_CAPTION"), vm.name_description, Guid.NewGuid().ToString(), vmtype);
                #endregion

                #region ADD CPUS
                OVF.SetCPUs(ovfEnv, vsId, (ulong)vm.VCPUs_max);
                #endregion

                #region ADD MEMORY
                OVF.SetMemory(ovfEnv, vsId, (ulong)(vm.memory_dynamic_max / MB), "MB");
                #endregion

                #region ADD NETWORKS
                List <XenRef <VIF> > vifs = VM.get_VIFs(xenSession, vmRef);
                foreach (XenRef <VIF> vifref in vifs)
                {
                    VIF vif = VIF.get_record(xenSession, vifref);
                    XenRef <Network> netRef = vif.network;
                    Network          net    = Network.get_record(xenSession, netRef);

                    // Why is the following call reference using name_label where other references use uuid?
                    OVF.AddNetwork(ovfEnv, vsId, net.uuid, net.name_label, net.name_description, vif.MAC);
                }
                #endregion

                #region SET STARTUP OPTIONS
                OVF.AddStartupSection(ovfEnv, true, vsId, vm.order, vm.start_delay, vm.shutdown_delay);
                #endregion

                #region GET AND EXPORT DISKS using iSCSI
                List <XenRef <VBD> > vbdlist = VM.get_VBDs(xenSession, vmRef);
                _vdiRefs.Clear();

                int diskIndex = 0;

                foreach (XenRef <VBD> vbdref in vbdlist)
                {
                    VBD vbd = VBD.get_record(xenSession, vbdref);

                    if (vbd.type == vbd_type.CD)
                    {
                        string rasdid = OVF.AddCDROM(ovfEnv, vsId, vbd.uuid, OVF.GetContentMessage("RASD_16_CAPTION"), OVF.GetContentMessage("RASD_16_DESCRIPTION"));
                        OVF.SetTargetDeviceInRASD(ovfEnv, vsId, rasdid, vbd.userdevice);
                    }
                    else
                    {
                        try
                        {
                            XenRef <VDI> vdi = VBD.get_VDI(xenSession, vbdref);
                            if (vdi != null && !string.IsNullOrEmpty(vdi.opaque_ref) && !(vdi.opaque_ref.ToLower().Contains("null")))
                            {
                                _vdiRefs.Add(vdi);
                                VDI    lVdi = VDI.get_record(xenSession, vdi);
                                string destinationFilename = Path.Combine(targetPath, string.Format(@"{0}.vhd", lVdi.uuid));
                                string diskid = Guid.NewGuid().ToString();

                                string diskName = lVdi.name_label;

                                if (diskName == null)
                                {
                                    diskName = string.Format("{0} {1}", OVF.GetContentMessage("RASD_19_CAPTION"), diskIndex);
                                }

                                OVF.AddDisk(ovfEnv, vsId, diskid, Path.GetFileName(destinationFilename), vbd.bootable, diskName, lVdi.name_description, (ulong)lVdi.physical_utilisation, (ulong)lVdi.virtual_size);
                                OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskid, vbd.userdevice);

                                diskIndex++;
                            }
                        }
                        catch (Exception ex)
                        {
                            log.InfoFormat("Export: VBD Skipped: {0}: {1}", vbdref, ex.Message);
                        }
                    }
                }
                #endregion

                if (!MetaDataOnly)
                {
                    _copydisks(ovfEnv, ovfname, targetPath);
                }

                #region ADD XEN SPECIFICS
                if (vm.HVM_boot_params != null)
                {
                    Dictionary <string, string> _params = vm.HVM_boot_params;
                    foreach (string key in _params.Keys)
                    {
                        if (key.ToLower().Equals("order"))
                        {
                            OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", _params[key], OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                        }
                    }
                }
                if (!string.IsNullOrEmpty(vm.HVM_boot_policy))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_policy", vm.HVM_boot_policy, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2"));
                }
                if (vm.HVM_shadow_multiplier != 1.0)
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_shadow_multiplier", Convert.ToString(vm.HVM_shadow_multiplier), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (vm.platform != null)
                {
                    Dictionary <string, string> platform = vm.platform;
                    StringBuilder sb = new StringBuilder();
                    foreach (string key in platform.Keys)
                    {
                        sb.AppendFormat(@"{0}={1};", key, platform[key]);
                    }
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3"));
                }
                if (!string.IsNullOrEmpty(vm.PV_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_args", vm.PV_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_bootloader))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader", vm.PV_bootloader, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_bootloader_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader_args", vm.PV_bootloader_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_kernel))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_kernel", vm.PV_kernel, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_legacy_args))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_legacy_args", vm.PV_legacy_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (!string.IsNullOrEmpty(vm.PV_ramdisk))
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_ramdisk", vm.PV_ramdisk, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }

                if (vm.VGPUs.Count != 0)
                {
                    VGPU vgpu = VGPU.get_record(xenSession, vm.VGPUs[0]);

                    if (vgpu != null)
                    {
                        var vgpuGroup = GPU_group.get_record(xenSession, vgpu.GPU_group);
                        var vgpuType  = VGPU_type.get_record(xenSession, vgpu.type);

                        var sb = new StringBuilder();
                        sb.AppendFormat("GPU_types={{{0}}};",
                                        vgpuGroup.GPU_types == null || vgpuGroup.GPU_types.Length < 1
                                            ? ""
                                            : string.Join(";", vgpuGroup.GPU_types));
                        sb.AppendFormat("VGPU_type_vendor_name={0};", vgpuType.vendor_name ?? "");
                        sb.AppendFormat("VGPU_type_model_name={0};", vgpuType.model_name ?? "");
                        OVF.AddOtherSystemSettingData(ovfEnv, vsId, "vgpu", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_4"));
                    }
                }
                #endregion

                OVF.FinalizeEnvelope(ovfEnv);
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                {
                    throw;
                }
                log.Error(Messages.ERROR_EXPORT_FAILED);
                throw new Exception(Messages.ERROR_EXPORT_FAILED, ex);
            }
            return(ovfEnv);
        }
Пример #3
0
        private void Build()
        {
            var pool = Helpers.GetPoolOfOne(connection);

            bool is_host = xenObjectCopy is Host;
            bool is_vm   = xenObjectCopy is VM && !((VM)xenObjectCopy).is_a_snapshot;
            bool is_sr   = xenObjectCopy is SR;

            bool is_pool    = xenObjectCopy is Pool;
            bool is_vdi     = xenObjectCopy is VDI;
            bool is_network = xenObjectCopy is XenAPI.Network;

            bool is_hvm     = is_vm && ((VM)xenObjectCopy).IsHVM;
            bool is_in_pool = Helpers.GetPool(xenObjectCopy.Connection) != null;

            bool is_pool_or_standalone = is_pool || (is_host && !is_in_pool);

            bool wlb_enabled = (Helpers.WlbEnabledAndConfigured(xenObjectCopy.Connection));

            bool is_VMPP = xenObjectCopy is VMPP;

            bool is_VM_appliance = xenObjectCopy is VM_appliance;

            ContentPanel.SuspendLayout();
            verticalTabs.BeginUpdate();

            try
            {
                verticalTabs.Items.Clear();

                ShowTab(GeneralEditPage = new GeneralEditPage());

                if (!is_VMPP && !is_VM_appliance)
                {
                    ShowTab(CustomFieldsEditPage = new CustomFieldsDisplayPage {
                        AutoScroll = true
                    });
                }

                if (is_vm)
                {
                    ShowTab(VCpuMemoryEditPage     = new CPUMemoryEditPage());
                    ShowTab(StartupOptionsEditPage = new BootOptionsEditPage());

                    if (!Helpers.BostonOrGreater(xenObjectCopy.Connection) && Helpers.FeatureForbidden(xenObjectCopy, Host.RestrictHAFloodgate))
                    {
                        VMHAUpsellEditPage = new UpsellPage {
                            Image = Properties.Resources._001_PowerOn_h32bit_16, Text = Messages.START_UP_OPTIONS
                        };
                        VMHAUpsellEditPage.SetAllTexts(Messages.UPSELL_BLURB_HA, InvisibleMessages.UPSELL_LEARNMOREURL_HA);
                        ShowTab(VMHAUpsellEditPage);
                    }
                    else
                    {
                        ShowTab(VMHAEditPage = new VMHAEditPage {
                            VerticalTabs = verticalTabs
                        });
                    }
                }

                if (is_vm || is_host || (is_sr && Helpers.ClearwaterOrGreater(connection)))
                {
                    if (Helpers.FeatureForbidden(xenObjectCopy, Host.RestrictAlerts))
                    {
                        PerfmonAlertUpsellEditPage = new UpsellPage {
                            Image = Properties.Resources._000_Alert2_h32bit_16, Text = Messages.ALERTS
                        };
                        PerfmonAlertUpsellEditPage.SetAllTexts(Messages.UPSELL_BLURB_ALERTS, InvisibleMessages.UPSELL_LEARNMOREURL_ALERTS);
                        ShowTab(PerfmonAlertUpsellEditPage);
                    }
                    else
                    {
                        ShowTab(PerfmonAlertEditPage = new PerfmonAlertEditPage {
                            AutoScroll = true
                        });
                    }
                }

                if (is_pool_or_standalone)
                {
                    if (Helpers.FeatureForbidden(xenObjectCopy, Host.RestrictAlerts))
                    {
                        PerfmonAlertOptionsUpsellEditPage = new UpsellPage {
                            Image = Properties.Resources._000_Email_h32bit_16, Text = Messages.EMAIL_OPTIONS
                        };
                        PerfmonAlertOptionsUpsellEditPage.SetAllTexts(Messages.UPSELL_BLURB_ALERTS, InvisibleMessages.UPSELL_LEARNMOREURL_ALERTS);
                        ShowTab(PerfmonAlertOptionsUpsellEditPage);
                    }
                    else
                    {
                        ShowTab(PerfmonAlertOptionsEditPage = new PerfmonAlertOptionsPage());
                    }

                    if (!Helpers.FeatureForbidden(xenObjectCopy, Host.RestrictStorageChoices) &&
                        !Helpers.BostonOrGreater(xenObjectCopy.Connection) &&
                        Helpers.MidnightRideOrGreater(xenObjectCopy.Connection))
                    {
                        ShowTab(StorageLinkPage = new StorageLinkEditPage());
                    }
                }

                if (is_host)
                {
                    ShowTab(hostMultipathPage1 = new HostMultipathPage());

                    if (Helpers.MidnightRideOrGreater(xenObject.Connection))
                    {
                        ShowTab(HostPowerONEditPage = new HostPowerONEditPage());
                    }

                    ShowTab(LogDestinationEditPage = new LogDestinationEditPage());
                }

                if (is_pool && Helpers.MidnightRideOrGreater(xenObject.Connection))
                {
                    ShowTab(PoolPowerONEditPage = new PoolPowerONEditPage());
                }

                if ((is_pool_or_standalone && Helpers.VGpuCapability(xenObjectCopy.Connection)) ||
                    (is_host && ((Host)xenObjectCopy).CanEnableDisableIntegratedGpu))
                {
                    ShowTab(PoolGpuEditPage = new PoolGpuEditPage());
                }

                if (is_network)
                {
                    ShowTab(editNetworkPage = new EditNetworkPage());
                }

                if (is_vm && !wlb_enabled)
                {
                    ShowTab(HomeServerPage = new HomeServerEditPage());
                }

                if (is_vm && ((VM)xenObjectCopy).CanHaveGpu)
                {
                    if (Helpers.BostonOrGreater(xenObject.Connection))
                    {
                        if (Helpers.FeatureForbidden(xenObjectCopy, Host.RestrictGpu))
                        {
                            GpuUpsellEditPage = new UpsellPage {
                                Image = Properties.Resources._000_GetMemoryInfo_h32bit_16, Text = Messages.GPU
                            };
                            GpuUpsellEditPage.SetAllTexts(Messages.UPSELL_BLURB_GPU, InvisibleMessages.UPSELL_LEARNMOREURL_GPU);
                            ShowTab(GpuUpsellEditPage);
                        }
                        else
                        {
                            ShowTab(GpuEditPage = new GpuEditPage());
                        }
                    }
                }

                if (is_hvm)
                {
                    ShowTab(VMAdvancedEditPage = new VMAdvancedEditPage());
                }

                if (is_vm && Helpers.ContainerCapability(xenObject.Connection) && ((VM)xenObjectCopy).CanBeEnlightened)
                {
                    ShowTab(VMEnlightenmentEditPage = new VMEnlightenmentEditPage());
                }

                if (is_vm && Helpers.ContainerCapability(xenObject.Connection) && ((VM)xenObjectCopy).CanHaveCloudConfigDrive)
                {
                    ShowTab(CloudConfigParametersPage = new Page_CloudConfigParameters());
                }

                if (is_VMPP)
                {
                    ShowTab(newPolicyVMsPage1 = new NewVMGroupVMsPage <VMPP> {
                        Pool = pool
                    });
                    ShowTab(newPolicySnapshotTypePage1      = new NewPolicySnapshotTypePage());
                    ShowTab(newPolicySnapshotFrequencyPage1 = new NewPolicySnapshotFrequencyPage {
                        Pool = pool
                    });
                    ShowTab(newPolicyArchivePage1 = new NewPolicyArchivePage {
                        Pool = pool, PropertiesDialog = this
                    });
                    ShowTab(newPolicyEmailPage1 = new NewPolicyEmailPage {
                        PropertiesDialog = this
                    });
                }

                if (is_VM_appliance)
                {
                    ShowTab(newVMApplianceVMsPage1 = new NewVMGroupVMsPage <VM_appliance> {
                        Pool = pool
                    });
                    ShowTab(newVmApplianceVmOrderAndDelaysPage1 = new NewVMApplianceVMOrderAndDelaysPage {
                        Pool = pool
                    });
                }

                //
                // Now add one tab per VBD (for VDIs only)
                //

                if (!is_vdi)
                {
                    return;
                }

                ShowTab(vdiSizeLocation = new VDISizeLocationPage());

                VDI vdi = xenObjectCopy as VDI;

                List <VBDEditPage> vbdEditPages = new List <VBDEditPage>();

                foreach (VBD vbd in vdi.Connection.ResolveAll(vdi.VBDs))
                {
                    VBDEditPage editPage = new VBDEditPage();

                    editPage.SetXenObjects(null, vbd);
                    vbdEditPages.Add(editPage);
                    ShowTab(editPage);
                }

                if (vbdEditPages.Count <= 0)
                {
                    return;
                }

                ActionProgressDialog dialog = new ActionProgressDialog(
                    new DelegatedAsyncAction(vdi.Connection, Messages.DEVICE_POSITION_SCANNING,
                                             Messages.DEVICE_POSITION_SCANNING, Messages.DEVICE_POSITION_SCANNED,
                                             delegate(Session session)
                {
                    foreach (VBDEditPage page in vbdEditPages)
                    {
                        page.UpdateDevicePositions(session);
                    }
                }),
                    ProgressBarStyle.Continuous);
                dialog.ShowCancel = true;
                dialog.ShowDialog(Program.MainWindow);
            }
            finally
            {
                ContentPanel.ResumeLayout();
                verticalTabs.EndUpdate();
                verticalTabs.SelectedIndex = 0;
            }
        }
Пример #4
0
 public LunPerVdiPickerItemWrapper(SR LUNsourceSr, VDI vdi) : base(LUNsourceSr, vdi)
 {
 }
Пример #5
0
        private void generatePoolHABox(Pool pool)
        {
            if (!pool.ha_enabled)
            {
                return;
            }

            // 'High Availability' heading
            CustomListRow header = CreateHeader(Messages.HA_CONFIGURATION_TITLE);

            customListPanel.AddRow(header);
            AddRow(header, GetFriendlyName("pool.ha_enabled"), pool, getPoolHAStatus, false);
            {
                // ntol row. May be red and bold.
                bool redBold = pool.ha_host_failures_to_tolerate == 0;

                CustomListRow newChild = CreateNewRow(Messages.HA_CONFIGURED_CAPACITY, new ToStringWrapper <Pool>(pool, getNtol), redBold);
                header.AddChild(newChild);

                if (redBold)
                {
                    newChild.Items[1].ForeColor = Color.Red;
                    ToolStripMenuItem editHa = new ToolStripMenuItem(Messages.CONFIGURE_HA_ELLIPSIS);
                    editHa.Click += delegate { EditHA(pool); };
                    newChild.MenuItems.Add(editHa);
                    newChild.DefaultMenuItem = editHa;
                }
                else
                {
                    newChild.Items[1].ForeColor = BaseTabPage.ItemValueForeColor;
                }
            }

            {
                // plan_exists_for row needs some special work: the text may be red and bold
                bool          redBold  = haStatusRed(pool);
                CustomListRow newChild = CreateNewRow(Messages.HA_CURRENT_CAPACITY, new ToStringWrapper <Pool>(pool, getPlanExistsFor), redBold);
                header.AddChild(newChild);

                if (redBold)
                {
                    newChild.Items[1].ForeColor = Color.Red;
                    ToolStripMenuItem editHa = new ToolStripMenuItem(Messages.CONFIGURE_HA_ELLIPSIS);
                    editHa.Click += delegate { EditHA(pool); };
                    newChild.MenuItems.Add(editHa);
                    newChild.DefaultMenuItem = editHa;
                }
                else
                {
                    newChild.Items[1].ForeColor = BaseTabPage.ItemValueForeColor;
                }
            }
            AddBottomSpacing(header);

            // 'Heartbeating status' heading
            header = CreateHeader(Messages.HEARTBEATING_STATUS);
            customListPanel.AddRow(header);

            // Now build the heartbeat target health table

            List <SR> heartbeatSRs = pool.GetHAHeartbeatSRs();

            // Sort heartbeat SRs using NaturalCompare
            heartbeatSRs.Sort((Comparison <SR>) delegate(SR a, SR b)
            {
                return(StringUtility.NaturalCompare(a.Name, b.Name));
            });

            List <Host> members = new List <Host>(pool.Connection.Cache.Hosts);

            // Sort pool members using NaturalCompare
            members.Sort((Comparison <Host>) delegate(Host a, Host b)
            {
                return(StringUtility.NaturalCompare(a.Name, b.Name));
            });
            int numCols = 1 + 2 + (2 * heartbeatSRs.Count); // Hostnames col, then 2 each for each HB target (network + SRs)
            int numRows = 1 + members.Count;

            // Create rows and cols
            tableLatencies.SuspendLayout();
            tableLatencies.ColumnCount = numCols;
            tableLatencies.ColumnStyles.Clear();
            for (int i = 0; i < numCols; i++)
            {
                tableLatencies.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            }
            tableLatencies.RowCount = numRows;
            tableLatencies.RowStyles.Clear();
            for (int i = 0; i < numRows; i++)
            {
                tableLatencies.RowStyles.Add(new RowStyle(SizeType.AutoSize));
            }

            {
                // Network icon
                PictureBox p = new PictureBox();
                p.Image    = Images.GetImage16For(Icons.Network);
                p.SizeMode = PictureBoxSizeMode.AutoSize;
                p.Padding  = new Padding(0);
                tableLatencies.Controls.Add(p);
                tableLatencies.SetCellPosition(p, new TableLayoutPanelCellPosition(1, 0));
                // Network text
                Label l = new Label();
                l.Padding   = new Padding(0, 5, 5, 5);
                l.Font      = BaseTabPage.ItemLabelFont;
                l.ForeColor = BaseTabPage.ItemLabelForeColor;
                l.AutoSize  = true;
                l.Text      = Messages.NETWORK;
                tableLatencies.Controls.Add(l);
                tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(2, 0));
            }

            for (int i = 0; i < heartbeatSRs.Count; i++)
            {
                // SR icon
                PictureBox p = new PictureBox();
                p.Image    = Images.GetImage16For(heartbeatSRs[i].GetIcon);
                p.SizeMode = PictureBoxSizeMode.AutoSize;
                p.Padding  = new Padding(0);
                tableLatencies.Controls.Add(p);
                tableLatencies.SetCellPosition(p, new TableLayoutPanelCellPosition((2 * i) + 3, 0));
                // SR name
                Label l = new Label();
                l.Padding      = new Padding(0, 5, 5, 5);
                l.Font         = BaseTabPage.ItemLabelFont;
                l.ForeColor    = BaseTabPage.ItemLabelForeColor;
                l.AutoSize     = false;
                l.Size         = new Size(200, 25);
                l.AutoEllipsis = true;
                l.Text         = heartbeatSRs[i].Name;
                tableLatencies.Controls.Add(l);
                tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition((2 * i) + 4, 0));
            }

            for (int i = 0; i < members.Count; i++)
            {
                // Server name label
                Label l = new Label();
                l.Padding   = new Padding(5);
                l.Font      = BaseTabPage.ItemLabelFont;
                l.ForeColor = BaseTabPage.ItemLabelForeColor;
                l.AutoSize  = true;
                l.Text      = members[i].Name.Ellipsise(30);
                tableLatencies.Controls.Add(l);
                tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(0, i + 1));

                // Network HB status
                l          = new Label();
                l.Padding  = new Padding(0, 5, 0, 5);
                l.Font     = BaseTabPage.ItemValueFont;
                l.AutoSize = true;
                if (members[i].ha_network_peers.Length == members.Count)
                {
                    l.ForeColor = Color.Green;
                }
                else
                {
                    l.ForeColor = BaseTabPage.ItemValueForeColor;
                }

                if (members[i].ha_network_peers.Length == 0)
                {
                    l.Text = Messages.HA_HEARTBEAT_UNHEALTHY;
                }
                else if (members[i].ha_network_peers.Length == members.Count)
                {
                    l.Text = Messages.HA_HEARTBEAT_HEALTHY;
                }
                else
                {
                    l.Text = string.Format(Messages.HA_HEARTBEAT_SERVERS, members[i].ha_network_peers.Length, members.Count);
                }
                tableLatencies.Controls.Add(l);
                tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(1, i + 1));
                tableLatencies.SetColumnSpan(l, 2);

                // For each heartbeat SR, show health from this host's perspective
                for (int j = 0; j < heartbeatSRs.Count; j++)
                {
                    l           = new Label();
                    l.Padding   = new Padding(0, 5, 0, 5);
                    l.Font      = BaseTabPage.ItemValueFont;
                    l.ForeColor = BaseTabPage.ItemValueForeColor;
                    l.AutoSize  = true;
                    l.Text      = Messages.HA_HEARTBEAT_UNHEALTHY;
                    foreach (string opaqueRef in members[i].ha_statefiles)
                    {
                        XenRef <VDI> vdiRef = new XenRef <VDI>(opaqueRef);
                        VDI          vdi    = pool.Connection.Resolve(vdiRef);
                        if (vdi == null)
                        {
                            continue;
                        }
                        SR sr = pool.Connection.Resolve(vdi.SR);
                        if (sr == null)
                        {
                            continue;
                        }
                        if (sr == heartbeatSRs[j])
                        {
                            l.ForeColor = Color.Green;
                            l.Text      = Messages.HA_HEARTBEAT_HEALTHY;
                            break;
                        }
                    }
                    tableLatencies.Controls.Add(l);
                    tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition((2 * j) + 2, i + 1));
                    tableLatencies.SetColumnSpan(l, 2);
                }
            }

            tableLatencies.ResumeLayout();
            tableLatencies.PerformLayout();
        }
Пример #6
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;
            }
        }
Пример #7
0
        private void RefreshButtons()
        {
            SelectedItemCollection vdis = SelectedVDIs;

            // Delete button
            // The user can see that this disk is attached to more than one VMs. Allow deletion of multiple VBDs (non default behaviour),
            // but don't allow them to be deleted if a running vm is using the disk (default behaviour).

            DeleteVirtualDiskCommand deleteCmd = new DeleteVirtualDiskCommand(Program.MainWindow, vdis)
            {
                AllowMultipleVBDDelete = true
            };

            if (deleteCmd.CanExecute())
            {
                RemoveButton.Enabled = true;
                RemoveButtonContainer.RemoveAll();
            }
            else
            {
                RemoveButton.Enabled = false;
                RemoveButtonContainer.SetToolTip(deleteCmd.ToolTipText);
            }

            // Move button
            Command moveCmd = MoveVirtualDiskDialog.MoveMigrateCommand(Program.MainWindow, vdis);

            if (moveCmd.CanExecute())
            {
                buttonMove.Enabled = true;
                toolTipContainerMove.RemoveAll();
            }
            else
            {
                buttonMove.Enabled = false;
                toolTipContainerMove.SetToolTip(moveCmd.ToolTipText);
            }

            // Rescan button
            if (sr == null || sr.Locked)
            {
                buttonRescan.Enabled = false;
            }
            else if (HelpersGUI.BeingScanned(sr))
            {
                buttonRescan.Enabled = false;
                toolTipContainerRescan.SetToolTip(Messages.SCAN_IN_PROGRESS_TOOLTIP);
            }
            else
            {
                buttonRescan.Enabled = true;
                toolTipContainerRescan.RemoveAll();
            }

            // Add VDI button
            addVirtualDiskButton.Enabled = sr != null && !sr.Locked;

            // Properties button
            if (vdis.Count == 1)
            {
                VDI vdi = vdis.AsXenObjects <VDI>()[0];
                EditButton.Enabled = sr != null && !sr.Locked && !vdi.is_a_snapshot && !vdi.Locked;
            }
            else
            {
                EditButton.Enabled = false;
            }
        }
Пример #8
0
        public NewDiskDialog(IXenConnection connection, VM vm, SrPicker.SRPickerType PickerUsage, VDI diskTemplate, Host affinity, bool canResize, long minSize, IEnumerable <VDI> vdiNamesInUse)
            : this(connection, vdiNamesInUse)
        {
            TheVM            = vm;
            DiskTemplate     = diskTemplate;
            CanResize        = canResize;
            MinSize          = minSize;
            this.PickerUsage = PickerUsage;
            SrListBox.SetAffinity(affinity);

            Pool pool_sr = Helpers.GetPoolOfOne(connection);

            if (pool_sr != null)
            {
                SrListBox.DefaultSR = connection.Resolve(pool_sr.default_SR); //if default sr resolves to null the first sr in the list will be selected
            }
            SrListBox.selectDefaultSROrAny();

            LoadValues();
        }
Пример #9
0
        private void OkButton_Click(object sender, EventArgs e)
        {
            if (SrListBox.SR == null || SelectionNull || NameTextBox.Text == "" || !connection.IsConnected)
            {
                return;
            }

            if (DontCreateVDI)
            {
                DialogResult = DialogResult.OK;
                Close();
                return;
            }
            XenAPI.SR sr = SrListBox.SR;
            if (!sr.shared && TheVM != null && TheVM.HaPriorityIsRestart())
            {
                DialogResult dialogResult;
                using (var dlg = new ThreeButtonDialog(
                           new ThreeButtonDialog.Details(SystemIcons.Warning, Messages.NEW_SR_DIALOG_ATTACH_NON_SHARED_DISK_HA, Messages.XENCENTER),
                           ThreeButtonDialog.ButtonYes,
                           ThreeButtonDialog.ButtonNo))
                {
                    dialogResult = dlg.ShowDialog(Program.MainWindow);
                }
                if (dialogResult != DialogResult.Yes)
                {
                    return;
                }
                new HAUnprotectVMAction(TheVM).RunExternal(TheVM.Connection.Session);
            }

            VDI vdi = NewDisk();


            if (TheVM != null)
            {
                var alreadyHasBootableDisk = HasBootableDisk(TheVM);

                Actions.DelegatedAsyncAction action = new Actions.DelegatedAsyncAction(connection,
                                                                                       string.Format(Messages.ACTION_DISK_ADDING_TITLE, NameTextBox.Text, sr.NameWithoutHost),
                                                                                       Messages.ACTION_DISK_ADDING, Messages.ACTION_DISK_ADDED,
                                                                                       delegate(XenAPI.Session session)
                {
                    // Get legitimate unused userdevice numbers
                    string[] uds = XenAPI.VM.get_allowed_VBD_devices(session, TheVM.opaque_ref);
                    if (uds.Length == 0)
                    {
                        throw new Exception(FriendlyErrorNames.VBDS_MAX_ALLOWED);
                    }
                    string ud      = uds[0];
                    string vdiref  = VDI.create(session, vdi);
                    XenAPI.VBD vbd = NewDevice();
                    vbd.VDI        = new XenAPI.XenRef <XenAPI.VDI>(vdiref);
                    vbd.VM         = new XenAPI.XenRef <XenAPI.VM>(TheVM);

                    // CA-44959: only make bootable if there aren't other bootable VBDs.
                    vbd.bootable   = ud == "0" && !alreadyHasBootableDisk;
                    vbd.userdevice = ud;

                    // Now try to plug the VBD.
                    new XenAdmin.Actions.VbdSaveAndPlugAction(TheVM, vbd, vdi.Name, session, false, ShowMustRebootBoxCD, ShowVBDWarningBox).RunAsync();
                });
                action.VM = TheVM;
                new Dialogs.ActionProgressDialog(action, ProgressBarStyle.Blocks).ShowDialog();
                if (!action.Succeeded)
                {
                    return;
                }
            }
            else
            {
                CreateDiskAction action = new CreateDiskAction(vdi);
                new Dialogs.ActionProgressDialog(action, ProgressBarStyle.Marquee).ShowDialog();
                if (!action.Succeeded)
                {
                    return;
                }
            }
            DialogResult = DialogResult.OK;
            Close();
        }
Пример #10
0
 /// <summary>
 /// Checks whether there is enough space available on the SR to accommodate a VDI.
 /// </summary>
 private static bool IsSufficientFreeSpaceAvailableOnSrForVdi(SR sr, VDI disk)
 {
     return(sr != null && sr.VdiCreationCanProceed(Helpers.GetRequiredSpaceToCreateVdiOnSr(sr, disk)));
 }
Пример #11
0
 public NewDiskDialog(IXenConnection connection, VM vm, VDI diskTemplate, Host affinity, bool canResize, long minSize, IEnumerable <VDI> vdiNamesInUse)
     : this(connection, vm, SrPicker.SRPickerType.VM, diskTemplate, affinity, canResize, minSize, vdiNamesInUse)
 {
 }
Пример #12
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;
        }
Пример #13
0
 /// <summary>
 /// Detaches a specific VDI from a specific VM (VBD unplug + VBD destroy)
 /// </summary>
 /// <param name="mainWindow"></param>
 /// <param name="vdi">The VDI to detach</param>
 /// <param name="vm">The VM to detach it from</param>
 public DetachVirtualDiskCommand(IMainWindow mainWindow, VDI vdi, VM vm)
     : base(mainWindow, vdi)
 {
     this.targetVM = vm;
 }
Пример #14
0
 /// <summary>
 /// Detaches the VDI from all VMs (VBD unplug + VBD destroy)
 /// </summary>
 /// <param name="mainWindow"></param>
 /// <param name="vdi"></param>
 public DetachVirtualDiskCommand(IMainWindow mainWindow, VDI vdi)
     : base(mainWindow, vdi)
 {
 }
Пример #15
0
        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)
                {
                    //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;
            }

            VM.set_suspend_SR(Session, VM.opaque_ref, suspendSr);
        }
Пример #16
0
        protected override string GetCantExecuteReasonCore(IXenObject item)
        {
            VBD vbd = item as VBD;

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

            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)
            {
                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_DEACTIVATE_SNAPSHOT_IN_USE
                    : vdiType == VDI.FriendlyType.ISO
                        ? Messages.CANNOT_DEACTIVATE_ISO_IN_USE
                        : Messages.CANNOT_DEACTIVATE_VDI_IN_USE);
            }

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

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

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

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

            return(base.GetCantExecuteReasonCore(item));
        }
Пример #17
0
 public DiskDescription(VDI disk, VBD device)
 {
     Disk   = disk;
     Device = device;
     Type   = DiskType.New;
 }
Пример #18
0
 public RemoveStorageLinkVolumeCommand(IMainWindow mainWindow, StorageLinkRepository slr, VDI vdi)
     : base(mainWindow, vdi)
 {
     _slr = slr;
 }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, sr.Name);

            String result;

            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", diskSize, sr.Name);

            VDI          vdi    = NewVDI(sr);
            XenRef <VDI> vdiRef = null;

            try
            {
                vdiRef = VDI.create(Session, vdi);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to create VDI", ex.Message);
                throw;
            }

            log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name, sr.Name);

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            try
            {
                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var actionPercent = (int)(((totalUploaded * 100) + percent) / totalCount);
                    Tick(actionPercent, Description);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "uploadTask", hostUrl);

                result = HTTPHelper.Put(progressDelegate, GetCancelling, true, Connection, RelatedTask, ref session, suppPackFilePath, hostUrl,
                                        (HTTP_actions.put_sss)HTTP_actions.put_import_raw_vdi,
                                        session.uuid, vdiRef.opaque_ref);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", "Failed to import a virtual disk via HTTP.", ex.Message);
                if (vdiRef != null)
                {
                    RemoveVDI(Session, vdiRef);
                }
                throw;
            }
            finally
            {
                Task.destroy(Session, RelatedTask);
                RelatedTask = null;
            }

            if (localStorageHost != null)
            {
                VdiRefs.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefs.Add(server, vdiRef);
                }
            }

            totalUploaded++;
            Description = String.Format(Messages.SUPP_PACK_UPLOADED, sr.Name);
            return(result);
        }
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, _updateName, sr.Name());
            log.DebugFormat("Creating vdi of size {0} bytes on SR '{1}'", _totalUpdateSize, sr.Name());

            VDI vdi    = NewVDI(sr);
            var vdiRef = VDI.create(Session, vdi);

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

            if (localStorageHost == null)
            {
                Uri uri = new Uri(Session.Url);
                hostUrl = uri.Host;
            }
            else
            {
                log.DebugFormat("SR is not shared -- redirecting to {0}", localStorageHost.address);
                hostUrl = localStorageHost.address;
            }

            log.DebugFormat("Using {0} for import", hostUrl);

            string result;

            try
            {
                log.DebugFormat("Uploading file '{0}' to VDI '{1}' on SR '{2}'", suppPackFilePath, vdi.Name(), sr.Name());

                HTTP.UpdateProgressDelegate progressDelegate = delegate(int percent)
                {
                    var sr1   = sr;
                    var descr = string.Format(Messages.UPLOAD_PATCH_UPLOADING_TO_SR_PROGRESS_DESCRIPTION, _updateName, sr1.Name(),
                                              Util.DiskSizeString(percent * _totalUpdateSize / 100, "F1"), Util.DiskSizeString(_totalUpdateSize));

                    var actionPercent = (int)((totalUploaded * 100 + percent) / totalCount);
                    ByteProgressDescription = descr;
                    Tick(actionPercent, descr);
                };

                Session session = NewSession();
                RelatedTask = Task.create(Session, "uploadTask", hostUrl);

                result = HTTPHelper.Put(progressDelegate, GetCancelling, true, Connection, RelatedTask, ref session, suppPackFilePath, hostUrl,
                                        (HTTP_actions.put_sss)HTTP_actions.put_import_raw_vdi,
                                        session.opaque_ref, vdiRef.opaque_ref);
            }
            catch (Exception ex)
            {
                log.Error("Failed to import a virtual disk over HTTP", ex);

                if (vdiRef != null)
                {
                    try
                    {
                        log.ErrorFormat("Deleting VDI '{0}' on a best effort basis.", vdiRef.opaque_ref);
                        Thread.Sleep(1000);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI.", removeEx);
                    }
                }

                //after having tried to remove the VDI, the original exception is thrown for the UI
                if (ex is TargetInvocationException && ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                Task.destroy(Session, RelatedTask);
                RelatedTask = null;
            }

            //introduce ISO for Ely and higher
            if (Helpers.ElyOrGreater(Connection))
            {
                try
                {
                    var poolUpdateRef = Pool_update.introduce(Connection.Session, vdiRef);
                    poolUpdate = Connection.WaitForCache(poolUpdateRef);

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                }
                catch (Exception ex)
                {
                    //clean-up the VDI we've just created
                    try
                    {
                        log.ErrorFormat("Deleting VDI '{0}' on a best effor basis.", vdiRef);
                        VDI.destroy(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        log.Error("Failed to remove VDI", removeEx);
                    }

                    var failure = ex as Failure;
                    if (failure != null && failure.ErrorDescription != null && failure.ErrorDescription.Count > 1 && failure.ErrorDescription[0] == Failure.UPDATE_ALREADY_EXISTS)
                    {
                        string uuidFound = failure.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, StringComparison.InvariantCultureIgnoreCase));
                    }
                    else
                    {
                        log.Error("Failed to introduce the update", ex);
                        poolUpdate = null;
                        throw;
                    }
                }
            }
            else
            {
                poolUpdate = null;
            }

            if (localStorageHost != null)
            {
                VdiRefsPerHost.Add(localStorageHost, vdiRef);
            }
            else // shared SR
            {
                foreach (var server in servers)
                {
                    VdiRefsPerHost.Add(server, vdiRef);
                }
            }

            totalUploaded++;
            Description = string.Format(Messages.SUPP_PACK_UPLOADED, sr.Name());

            foreach (Host host in servers)
            {
                SrsWithUploadedUpdatesPerHost[host] = sr;
            }

            return(result);
        }
Пример #21
0
            private VirtualTreeNode AddVDINode(VDI vdi)
            {
                String name = String.IsNullOrEmpty(vdi.Name) ? Messages.NO_NAME : vdi.Name;

                return(AddNode(name, Images.GetIconFor(vdi), false, vdi));
            }
Пример #22
0
 public LunComboBoxItem(VDI vdi)
 {
     Debug.Assert(vdi != null, "VDI passed to combobox was null");
     Vdi = vdi;
     AdditionalConstraints = new List <Predicate <VDI> >();
 }
Пример #23
0
 /// <summary>
 /// Checks whether there is enough space available on the SR to accommodate a VDI.
 /// </summary>
 private static bool IsSufficientFreeSpaceAvailableOnSrForVdi(SR sr, VDI disk)
 {
     return(sr != null && !sr.IsFull() && sr.FreeSpace() > Helpers.GetRequiredSpaceToCreateVdiOnSr(sr, disk));
 }
Пример #24
0
        protected override void Run()
        {
            Description     = string.Format(Messages.ACTION_MOVING_VDI, 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.MOVED;
            log.DebugFormat("Moved VDI '{0}'", Helpers.GetName(vdi));
        }
Пример #25
0
        private void _copydisks(EnvelopeType ovfEnv, string label, string targetPath)
        {
            m_iscsi = new iSCSI
            {
                UpdateHandler = iscsi_UpdateHandler,
                Cancel        = Cancel                 //in case it has already been cancelled
            };
            m_iscsi.ConfigureTvmNetwork(m_networkUuid, m_isTvmIpStatic, m_tvmIpAddress, m_tvmSubnetMask, m_tvmGateway);

            try
            {
                foreach (XenRef <VDI> vdiuuid in _vdiRefs)
                {
                    string uuid = "";
                    string destinationFilename = "";

                    try
                    {
                        uuid = VDI.get_uuid(XenSession, vdiuuid);
                        destinationFilename = Path.Combine(targetPath, string.Format(@"{0}.vhd", uuid));

                        if (File.Exists(destinationFilename))
                        {
                            destinationFilename = Path.Combine(targetPath, string.Format(@"{0}_{1}.vhd", uuid, Thread.CurrentThread.ManagedThreadId));
                            OVF.UpdateFilename(ovfEnv, string.Format(@"{0}.vhd", uuid), string.Format(@"{0}_{1}.vhd", uuid, Thread.CurrentThread.ManagedThreadId));
                            log.InfoFormat("{0}: VHD Name collision, renamed {1}.vhd to {1}_{2}.vhd",
                                           label, uuid, Thread.CurrentThread.ManagedThreadId);
                        }

                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOn, "Export", string.Format(Messages.FILES_TRANSPORT_SETUP, uuid + ".vhd")));

                        using (Stream source = m_iscsi.Connect(XenSession, uuid, true))
                        {
                            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOff, "Export", ""));
                            using (FileStream fs = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
                            {
                                // Create a geometry to give to DiscUtils.Vhd.Disk.InitializeDynamic() just so it doesn't override capacity
                                // when initializing the .
                                DiscUtils.Geometry geometry = DiscUtils.Geometry.FromCapacity(source.Length);

                                using (DiscUtils.Vhd.Disk destination = DiscUtils.Vhd.Disk.InitializeDynamic(fs, Ownership.None, source.Length, geometry))
                                {
                                    m_iscsi.Copy(source, destination.Content, Path.GetFileName(destinationFilename), ShouldVerifyDisks);
                                }
                            }
                        }

                        if (ShouldVerifyDisks)
                        {
                            using (var target = new DiscUtils.Vhd.Disk(destinationFilename, FileAccess.Read))
                            {
                                m_iscsi.Verify(target.Content, destinationFilename);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is OperationCanceledException)
                        {
                            throw;
                        }
                        var msg = string.Format(Messages.ISCSI_COPY_ERROR, destinationFilename);
                        log.Error(msg);
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.Failure, "Export", msg, ex));
                        throw new Exception(msg, ex);
                    }
                    finally
                    {
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOn, "Export", string.Format(Messages.FILES_TRANSPORT_CLEANUP, uuid + ".vhd")));
                        m_iscsi.Disconnect(XenSession);
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOff, "Export", ""));
                    }
                }
            }
            finally
            {
                _vdiRefs.Clear();
            }
        }
Пример #26
0
        private void RefreshButtons()
        {
            bool srLocked = sr == null || sr.Locked;
            SelectedItemCollection vdis = SelectedVDIs;

            // Delete button
            DeleteVirtualDiskCommand deleteCmd = new DeleteVirtualDiskCommand(Program.MainWindow, vdis);

            // User has visibility that this disk is related to all it's VM. Allow deletion with multiple VBDs (non default behaviour),
            // but don't allow them to delete if a running vm is using the disk (default behaviour).
            deleteCmd.AllowMultipleVBDDelete = true;
            if (deleteCmd.CanExecute())
            {
                RemoveButton.Enabled = true;
                RemoveButtonContainer.RemoveAll();
            }
            else
            {
                RemoveButton.Enabled = false;
                RemoveButtonContainer.SetToolTip(deleteCmd.ToolTipText);
            }

            // Move button
            Command moveCmd = MoveMigrateCommand(vdis);

            if (moveCmd.CanExecute())
            {
                buttonMove.Enabled = true;
                toolTipContainerMove.RemoveAll();
            }
            else
            {
                buttonMove.Enabled = false;
                toolTipContainerMove.SetToolTip(moveCmd.ToolTipText);
            }

            // Rescan button
            if (srLocked)
            {
                buttonRefresh.Enabled = false;
            }
            else if (HelpersGUI.BeingScanned(sr))
            {
                buttonRefresh.Enabled = false;
                toolTipContainerRescan.SetToolTip(Messages.SCAN_IN_PROGRESS_TOOLTIP);
            }
            else
            {
                buttonRefresh.Enabled = true;
                toolTipContainerRescan.RemoveAll();
            }

            // Add VDI button
            addVirtualDiskButton.Enabled = !srLocked;

            // Properties button
            if (vdis.Count == 1)
            {
                VDI vdi = vdis.AsXenObjects <VDI>()[0];
                EditButton.Enabled = !srLocked && !vdi.is_a_snapshot && !vdi.Locked;
            }
            else
            {
                EditButton.Enabled = false;
            }

            // Remove drop down button
            removeDropDownButton.Enabled = deleteCmd.CanExecute();
        }
Пример #27
0
        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);
        }
Пример #28
0
        protected override void Run()
        {
            Description = String.Format(Messages.ACTION_VDI_LOAD_METADATA_STATUS, Connection.Resolve(_poolMetadata.Vdi.SR).Name());
            log.DebugFormat("Loading metadata from VDI '{0}' on SR '{1}'", _poolMetadata.Vdi.Name(),
                            Connection.Resolve(_poolMetadata.Vdi.SR).Name());

            MetadataSessionRef = VDI.open_database(Session, _poolMetadata.Vdi.opaque_ref);
            PercentComplete    = 30;

            if (MetadataSessionRef != null)
            {
                MetadataSession = null;
                try
                {
                    MetadataSession = Session.get_record(Session, MetadataSessionRef);

                    #region FIND POOL
                    Dictionary <XenRef <XenAPI.Pool>, XenAPI.Pool> pools = XenAPI.Pool.get_all_records(MetadataSession);
                    foreach (var pool in pools.Values)
                    {
                        _poolMetadata.Pool = pool;
                        string poolName = String.IsNullOrEmpty(pool.name_label) && pool.master != null
                                              ? XenAPI.Host.get_name_label(MetadataSession, pool.master.opaque_ref)
                                              : pool.name_label;

                        _poolMetadata.Pool.name_label = poolName;
                        log.DebugFormat("Found metadata of pool '{0}' (UUID={1})", _poolMetadata.Pool.Name(),
                                        _poolMetadata.Pool.uuid);
                        break;
                    }
                    #endregion

                    /*if (_poolMetadata.Pool.uuid == Pool.uuid) // metadata of current pool
                     * {
                     *  return;
                     * }*/

                    _poolMetadata.VmAppliances = VM_appliance.get_all_records(MetadataSession);
                    foreach (var vmAppRef in _poolMetadata.VmAppliances.Keys)
                    {
                        _poolMetadata.VmAppliances[vmAppRef].opaque_ref = vmAppRef.opaque_ref;
                    }

                    PercentComplete = 50;

                    Dictionary <XenRef <VM>, VM> vms = VM.get_all_records(MetadataSession);
                    foreach (var vmRef in vms.Keys)
                    {
                        VM vm = vms[vmRef];
                        if (vm.not_a_real_vm())
                        {
                            continue;
                        }
                        vm.opaque_ref = vmRef.opaque_ref;
                        _poolMetadata.Vms.Add(vmRef, vm);
                    }
                }
                catch (Exception)
                {
                }
            }
            PercentComplete = 100;
            Description     = Messages.ACTION_VDI_LOAD_METADATA_DONE;
        }
Пример #29
0
        public CreateVMAction(IXenConnection connection, VM template, Host copyBiosStringsFrom,
                              string name, string description, InstallMethod installMethod,
                              string pvArgs, VDI cd, string url, BootMode bootMode, Host homeServer, long vcpusMax, long vcpusAtStartup,
                              long memoryDynamicMin, long memoryDynamicMax, long memoryStaticMax,
                              List <DiskDescription> disks, SR fullCopySR, List <VIF> vifs, bool startAfter,
                              Action <VM, bool> warningDialogHAInvalidConfig,
                              Action <VMStartAbstractAction, Failure> startDiagnosisForm,
                              List <VGPU> vGpus, bool modifyVgpuSettings, long coresPerSocket, string cloudConfigDriveTemplateText)
            : base(connection, string.Format(Messages.CREATE_VM, name),
                   string.Format(Messages.CREATE_VM_FROM_TEMPLATE, name, Helpers.GetName(template)))
        {
            Template            = template;
            CopyBiosStringsFrom = copyBiosStringsFrom;
            FullCopySR          = fullCopySR;
            NameLabel           = name;
            NameDescription     = description;
            InsMethod           = installMethod;
            PvArgs           = pvArgs;
            Cd               = cd;
            Url              = url;
            BootMode         = bootMode;
            HomeServer       = homeServer;
            VcpusMax         = vcpusMax;
            VcpusAtStartup   = vcpusAtStartup;
            MemoryDynamicMin = memoryDynamicMin;
            MemoryDynamicMax = memoryDynamicMax;
            MemoryStaticMax  = memoryStaticMax;
            Disks            = disks;
            Vifs             = vifs;
            StartAfter       = startAfter;
            _warningDialogHAInvalidConfig = warningDialogHAInvalidConfig;
            _startDiagnosisForm           = startDiagnosisForm;
            this.vGpus     = vGpus;
            CoresPerSocket = coresPerSocket;
            this.cloudConfigDriveTemplateText = cloudConfigDriveTemplateText;

            Pool pool_of_one = Helpers.GetPoolOfOne(Connection);

            if (HomeServer != null || pool_of_one != null) // otherwise we have no where to put the action
            {
                AppliesTo.Add(HomeServer != null ? HomeServer.opaque_ref : pool_of_one.opaque_ref);
            }

            assignOrRemoveVgpu = vGpus != null && vGpus.Count > 0 || modifyVgpuSettings && Helpers.GpuCapability(Connection);

            #region RBAC Dependencies

            if (StartAfter)
            {
                ApiMethodsToRoleCheck.Add("vm.start");
            }
            if (HomeServerChanged())
            {
                ApiMethodsToRoleCheck.Add("vm.set_affinity");
            }
            if (Template.memory_dynamic_min != MemoryDynamicMin || Template.memory_dynamic_max != MemoryDynamicMax || Template.memory_static_max != MemoryStaticMax)
            {
                ApiMethodsToRoleCheck.Add("vm.set_memory_limits");
            }

            if (assignOrRemoveVgpu)
            {
                ApiMethodsToRoleCheck.Add("VGPU.destroy");
                ApiMethodsToRoleCheck.Add("VGPU.create");
            }

            ApiMethodsToRoleCheck.AddRange(StaticRBACDependencies);

            ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList);
            ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList);

            #endregion
        }
Пример #30
0
 public DiskListVdiItem(VDI vdi)
 {
     TheVDI = vdi;
     Update();
 }