Пример #1
0
        // Find a name to use of a VM within an envelope that could have come from any hypervisor.
        // TODO: Consider refactoring this method because it is very similar to OVF.FindSystemName().
        private string FindVMName(EnvelopeType ovfEnv, string systemid)
        {
            VirtualSystem_Type vSystem = OVF.FindVirtualSystemById(ovfEnv, systemid);

            // Use the given name if present and valid.
            // The given name is Envelope.VirtualSystem.Name specified in the OVF Specification 1.1 clause 7.2.
            // XenServer sets the name property.
            // vSphere 4.1 and Virtual Box 4.0.6 do not.
            if ((Tools.ValidateProperty("Name", vSystem)) && !String.IsNullOrEmpty(vSystem.Name[0].Value))
            {
                return(vSystem.Name[0].Value);
            }

            // The VM wasn't given a name.
            // Build a list of choices from various properties.
            var choices = new List <string>();

            // VirtualSystem.id is next preference because vSphere and Virtual Box typically set this property to the VM name.
            if (!string.IsNullOrEmpty(vSystem.id))
            {
                choices.Add(vSystem.id);
            }

            // VirtualHardwareSection_Type.VirtualSystemIdentifier is next preference because Virtual Box will also set this property to the VM name.
            VirtualHardwareSection_Type[] vhsList = OVF.FindVirtualHardwareSection(ovfEnv, systemid);

            foreach (VirtualHardwareSection_Type vhs in vhsList)
            {
                if (vhs == null || vhs.System == null)
                {
                    continue;
                }

                if (Tools.ValidateProperty("VirtualSystemIdentifier", vhs.System))
                {
                    choices.Add(vhs.System.VirtualSystemIdentifier.Value);
                }
            }

            // Operating system description is next preference.
            OperatingSystemSection_Type[] ossList = OVF.FindSections <OperatingSystemSection_Type>(vSystem.Items);

            foreach (OperatingSystemSection_Type oss in ossList)
            {
                if (Tools.ValidateProperty("Description", oss))
                {
                    choices.Add(oss.Description.Value);
                }
            }

            // Envelope name is the last preference for XenServer that can could be a path in some cases.
            // vSphere and Virtual Box usually don't set this property.
            choices.Add(Path.GetFileNameWithoutExtension(ovfEnv.Name));

            // Last preference is file name.
            choices.Add(Path.GetFileNameWithoutExtension(m_pageImportSource.SelectedOvfPackage.PackageSourceFile));

            // First choice is one that is not a GUID.
            foreach (var choice in choices)
            {
                if (!String.IsNullOrEmpty(choice) && !IsGUID(choice))
                {
                    return(choice);
                }
            }

            // Second choice is the first GUID.
            foreach (var choice in choices)
            {
                if (!String.IsNullOrEmpty(choice))
                {
                    return(choice);
                }
            }

            // Last resort is a new GUID.
            return(Guid.NewGuid().ToString());
        }
Пример #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.hardware_platform_version >= 0)
                {
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
                }
                if (vm.has_vendor_device)
                {
                    //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type
                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), 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"));
                    }
                }

                string pvsSiteUuid = string.Empty;
                var    allProxies  = xenSession.Connection.Cache.PVS_proxies;

                foreach (var p in allProxies.Where(p => p != null && p.VIF != null))
                {
                    var vif = xenSession.Connection.Resolve(p.VIF);
                    if (vif != null)
                    {
                        var vmFromVif = xenSession.Connection.Resolve(vif.VM);
                        if (vmFromVif != null && vmFromVif.uuid == vm.uuid)
                        {
                            var pvsSite = xenSession.Connection.Resolve(p.site);
                            if (pvsSite != null)
                            {
                                pvsSiteUuid = pvsSite.uuid;
                            }

                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(pvsSiteUuid))
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid));

                    OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5"));
                }
                #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
        protected override void Run()
        {
            SafeToExit = false;
            var session = Connection.Session;
            var url     = session.Url;
            Uri uri     = new Uri(url);

            var appFolder = Path.Combine(m_applianceDirectory, m_applianceFileName);
            var appFile   = string.Format("{0}.ovf", m_applianceFileName);

            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }
            PercentComplete = 5;

            Description = Messages.EXPORTING_VMS;
            EnvelopeType env;

            try
            {
                m_transportAction = new XenOvfTransport.Export(uri, session)
                {
                    UpdateHandler     = UpdateHandler,
                    ShouldVerifyDisks = m_shouldVerify,
                    Cancel            = Cancelling                                  //in case the Cancel button has already been pressed
                };
                m_transportAction.SetTvmNetwork(m_networkUuid, m_isTvmIpStatic, m_tvmIpAddress, m_tvmSubnetMask, m_tvmGateway);
                env             = (m_transportAction as XenOvfTransport.Export).Process(appFolder, m_applianceFileName, (from VM vm in m_vmsToExport select vm.uuid).ToArray());
                PercentComplete = 60;
            }
            catch (OperationCanceledException)
            {
                throw new CancelledException();
            }

            foreach (var eula in m_eulas)
            {
                if (Cancelling)
                {
                    throw new CancelledException();
                }
                Description = Messages.ADDING_EULAS;
                OVF.AddEula(env, eula);
            }

            if (Cancelling)
            {
                throw new CancelledException();
            }

            var ovfPath = Path.Combine(appFolder, appFile);

            Description = String.Format(Messages.CREATING_FILE, appFile);
            OVF.SaveAs(env, ovfPath);
            PercentComplete = 70;

            if (Cancelling)
            {
                throw new CancelledException();
            }

            if (m_signAppliance)
            {
                Description = Messages.SIGNING_APPLIANCE;
                OVF.Sign(m_certificate, appFolder, appFile);
            }
            else if (m_createManifest)
            {
                Description = Messages.CREATING_MANIFEST;
                OVF.Manifest(appFolder, appFile);
            }

            PercentComplete = 90;

            if (Cancelling)
            {
                throw new CancelledException();
            }

            if (m_createOVA)
            {
                Description = String.Format(Messages.CREATING_FILE, String.Format("{0}.ova", m_applianceFileName));
                OVF.ConvertOVFtoOVA(appFolder, appFile, m_compressOVFfiles);
            }
            else if (m_compressOVFfiles)
            {
                Description  = Messages.COMPRESSING_FILES;
                m_compressor = new OvfCompressor {
                    CancelCompression = Cancelling
                };                                                                                   //in case the Cancel button has already been pressed}

                try
                {
                    m_compressor.CompressOvfFiles(ovfPath, "GZip");
                }
                catch (OperationCanceledException)
                {
                    throw new CancelledException();
                }
            }

            PercentComplete = 100;
            Description     = Messages.COMPLETED;
        }
Пример #4
0
        protected override void Run()
        {
            SafeToExit = false;
            if (m_verifySignature)
            {
                Description = Messages.VERIFYING_SIGNATURE;

                try
                {
                    // The appliance is known to have a signature and the user asked to verify it.
                    m_package.VerifySignature();

                    // If the appliance has a signature, then it has a manifest.
                    // Always verify the manifest after verifying the signature.
                    m_package.VerifyManifest();
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format(Messages.VERIFYING_SIGNATURE_ERROR, e.Message));
                }
            }
            else if (m_verifyManifest)
            {
                Description = Messages.VERIFYING_MANIFEST;

                try
                {
                    // The appliance had a manifest without a signature and the user asked to verify it.
                    // VerifyManifest() throws an exception when verification fails for any reason.
                    m_package.VerifyManifest();
                }
                catch (Exception e)
                {
                    throw new Exception(String.Format(Messages.VERIFYING_MANIFEST_ERROR, e.Message));
                }
            }

            List <string> validationErrors;

            OVF.Validate(m_package.PackageSourceFile, out validationErrors);

            PercentComplete = 20;
            Description     = Messages.IMPORTING_VMS;

            var session = Connection.Session;
            var url     = session.Url;
            Uri uri     = new Uri(url);

            //create a copy of the OVF
            var envelopes = new List <EnvelopeType>();

            foreach (var vmMapping in m_vmMappings)
            {
                if (Cancelling)
                {
                    throw new CancelledException();
                }

                string         systemid = vmMapping.Key;
                var            mapping  = vmMapping.Value;
                EnvelopeType[] envs     = OVF.Split(m_ovfEnvelope, "system", new object[] { new[] { systemid } });

                //storage
                foreach (var kvp in mapping.Storage)
                {
                    OVF.SetTargetSRInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                foreach (var kvp in mapping.StorageToAttach)
                {
                    OVF.SetTargetVDIInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                //network
                foreach (var kvp in mapping.Networks)
                {
                    OVF.SetTargetNetworkInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                if (m_runfixups)
                {
                    string cdId = OVF.SetRunOnceBootCDROMOSFixup(envs[0], systemid, Path.GetDirectoryName(m_package.PackageSourceFile));
                    OVF.SetTargetISOSRInRASD(envs[0], systemid, cdId, m_selectedIsoSr.uuid);
                }

                envelopes.Add(envs[0]);
            }

            var          appName = GetApplianceName(m_ovfEnvelope, m_package);
            EnvelopeType env     = OVF.Merge(envelopes, appName);

            try             //importVM
            {
                m_transportAction = new Import(uri, session)
                {
                    ApplianceName = appName,
                    UpdateHandler = UpdateHandler,
                    Cancel        = Cancelling                                                              //in case the Cancel button has already been pressed
                };
                m_transportAction.SetTvmNetwork(m_networkUuid, m_isTvmIpStatic, m_tvmIpAddress, m_tvmSubnetMask, m_tvmGateway);
                (m_transportAction as Import).Process(env, Path.GetDirectoryName(m_package.PackageSourceFile), m_password);
            }
            catch (OperationCanceledException)
            {
                throw new CancelledException();
            }

            PercentComplete = 100;
            Description     = Messages.COMPLETED;
        }
Пример #5
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();
            }
        }
Пример #6
0
        protected override void RunCore()
        {
            // The appliance has a signature and the user asked to verify it.
            if (m_verifySignature)
            {
                Description = Messages.VERIFYING_SIGNATURE;

                try
                {
                    m_package.VerifySignature();
                    log.Info($"Verified signature for package {m_package.Name}");
                }
                catch (Exception e)
                {
                    log.Error($"Signature verification failed for package {m_package.Name}", e);
                    throw new Exception(String.Format(Messages.VERIFYING_SIGNATURE_ERROR, e.Message));
                }
            }

            // The appliance has
            // - a signature (in which case it also has a manifest that should be verified AFTER the signature); or
            // - a manifest without a signature
            // and the user asked to verify it

            if (m_verifySignature || m_verifyManifest)
            {
                Description = Messages.VERIFYING_MANIFEST;

                try
                {
                    m_package.VerifyManifest();
                    log.Info($"Verified manifest for package {m_package.Name}");
                }
                catch (Exception e)
                {
                    log.Error($"Manifest verification failed for package {m_package.Name}", e);
                    throw new Exception(String.Format(Messages.VERIFYING_MANIFEST_ERROR, e.Message));
                }
            }

            PercentComplete = 20;
            Description     = string.Format(Messages.IMPORT_APPLIANCE_PREPARING, m_package.Name);

            //create a copy of the OVF
            var envelopes = new List <EnvelopeType>();

            foreach (var vmMapping in m_vmMappings)
            {
                CheckForCancellation();

                string         systemid = vmMapping.Key;
                var            mapping  = vmMapping.Value;
                EnvelopeType[] envs     = OVF.Split(m_package.OvfEnvelope, "system", new object[] { new[] { systemid } });

                //storage
                foreach (var kvp in mapping.Storage)
                {
                    OVF.SetTargetSRInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                foreach (var kvp in mapping.StorageToAttach)
                {
                    OVF.SetTargetVDIInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                //network
                foreach (var kvp in mapping.Networks)
                {
                    OVF.SetTargetNetworkInRASD(envs[0], systemid, kvp.Key, kvp.Value.uuid);
                }

                if (m_runfixups)
                {
                    string cdId = OVF.SetRunOnceBootCDROMOSFixup(envs[0], systemid, Path.GetDirectoryName(m_package.PackageSourceFile));
                    OVF.SetTargetISOSRInRASD(envs[0], systemid, cdId, m_selectedIsoSr.uuid);
                }

                envelopes.Add(envs[0]);
            }

            EnvelopeType env = OVF.Merge(envelopes, m_package.Name);

            object importedObject;

            try             //import VMs
            {
                m_package.ExtractToWorkingDir(CheckForCancellation);
                CheckForCancellation();
                OVF.ParseEncryption(env, out m_encryptionClass, out m_encryptionVersion);
                importedObject = Process(env, m_package.WorkingDir, m_package.Name);
            }
            catch (OperationCanceledException)
            {
                throw new CancelledException();
            }
            finally
            {
                m_package.CleanUpWorkingDir();
            }

            PercentComplete = 100;
            Description     = Messages.COMPLETED;

            if (_startAutomatically && importedObject is XenRef <VM_appliance> applianceRef)
            {
                var appliance = Connection.Resolve(applianceRef);
                if (appliance != null)
                {
                    new StartApplianceAction(appliance, false).RunAsync();
                }
            }
        }
Пример #7
0
        private bool CheckFixupIsoInXencenterInstallation(out string error)
        {
            error = string.Empty;

            var theVdi = Connection.Cache.VDIs.FirstOrDefault(vdi => vdi != null && vdi.name_label == OVF.GetISOFixupFileName());

            if (theVdi != null || File.Exists(OVF.GetISOFixupPath()))
            {
                return(true);
            }

            error = Messages.IMPORT_OPTIONS_PAGE_ERROR_NO_FIXUP_ISO_INSTALLED;
            return(false);
        }
Пример #8
0
        protected override void RunCore()
        {
            log.Info($"Exporting VMs to package {m_applianceFileName}");

            var appFolder = Path.Combine(m_applianceDirectory, m_applianceFileName);
            var appFile   = string.Format("{0}.ovf", m_applianceFileName);

            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }

            var envList = new List <EnvelopeType>();

            for (int i = 0; i < m_vmsToExport.Count; i++)
            {
                var vm = m_vmsToExport[i];
                CheckForCancellation();
                Description = string.Format(Messages.EXPORTING_VM_PREPARE, vm.Name());

                int curVm = i;
                void UpdatePercentage(float x)
                {
                    PercentComplete = (int)((curVm + x) * 80 / m_vmsToExport.Count);
                }

                try
                {
                    var envelope = Export(appFolder, vm, UpdatePercentage);
                    envList.Add(envelope);
                    PercentComplete = (i + 1) * 80 / m_vmsToExport.Count;
                }
                catch (OperationCanceledException)
                {
                    throw new CancelledException();
                }
            }

            EnvelopeType env = OVF.Merge(envList, m_applianceFileName);

            PercentComplete = 80;

            foreach (var eula in m_eulas)
            {
                CheckForCancellation();
                Description = Messages.ADDING_EULAS;
                OVF.AddEula(env, eula);
            }

            CheckForCancellation();
            var ovfPath = Path.Combine(appFolder, appFile);

            OVF.SaveAs(env, ovfPath);
            PercentComplete = 85;

            CheckForCancellation();

            if (m_createOVA)
            {
                ManifestAndSign(env, appFolder, appFile);
                PercentComplete = 90;
                log.Info($"Archiving OVF package {m_applianceFileName} into OVA");
                Description = string.Format(Messages.CREATING_OVA_FILE, string.Format("{0}.ova", m_applianceFileName));
                OVF.ConvertOVFtoOVA(env, ovfPath, CheckForCancellation, m_compressOVFfiles);
            }
            else if (m_compressOVFfiles)
            {
                log.Info($"Compressing package {m_applianceFileName}");
                Description = Messages.COMPRESSING_FILES;
                OVF.CompressFiles(env, ovfPath, CompressionFactory.Type.Gz, CheckForCancellation);
                PercentComplete = 95;
                ManifestAndSign(env, appFolder, appFile);
            }
            else
            {
                ManifestAndSign(env, appFolder, appFile);
            }

            PercentComplete = 100;
            Description     = Messages.COMPLETED;
        }
Пример #9
0
 public OvfStorageResourceContainer(EnvelopeType selectedOvfEnvelope, string sysId)
 {
     rasdArray = OVF.FindDiskRasds(selectedOvfEnvelope, sysId);
     this.selectedOvfEnvelope = selectedOvfEnvelope;
 }
Пример #10
0
        public override void CheckPageDisabled()
        {
            bool eulaExists = OVF.HasEula(SelectedOvfEnvelope);

            DisableStep = !eulaExists;
        }
Пример #11
0
        protected override void UpdateWizardContent(XenTabPage page)
        {
            Type type = page.GetType();

            if (type == typeof(ImportSourcePage))
            {
                #region ImportSourcePage

                var oldTypeOfImport = m_typeOfImport;                //store previous type
                m_typeOfImport = m_pageImportSource.TypeOfImport;
                var appliancePages = new XenTabPage[] { m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions };
                var imagePages     = new XenTabPage[] { m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions };
                var xvaPages       = new XenTabPage[] { m_pageXvaHost, m_pageXvaStorage, m_pageXvaNetwork };

                switch (m_typeOfImport)
                {
                case ImportType.Ovf:
                    if (oldTypeOfImport != ImportType.Ovf)
                    {
                        Text = Messages.WIZARD_TEXT_IMPORT_OVF;
                        pictureBoxWizard.Image = Images.StaticImages._000_ImportVirtualAppliance_h32bit_32;
                        RemovePages(imagePages);
                        RemovePage(m_pageBootOptions);
                        RemovePages(xvaPages);
                        AddAfterPage(m_pageImportSource, appliancePages);
                    }

                    m_pageEula.SelectedOvfEnvelope    = m_pageImportSource.SelectedOvfPackage.OvfEnvelope;
                    m_pageSecurity.SelectedOvfPackage = m_pageImportSource.SelectedOvfPackage;

                    CheckDisabledPages(m_pageEula, m_pageSecurity);                             //decide whether to disable these progress steps
                    ResetVmMappings(m_pageImportSource.SelectedOvfPackage.OvfEnvelope);
                    m_pageHost.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope;
                    m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject);
                    m_pageHost.VmMappings                    = m_vmMappings;
                    m_pageStorage.SelectedOvfEnvelope        = m_pageImportSource.SelectedOvfPackage.OvfEnvelope;
                    lunPerVdiMappingPage.SelectedOvfEnvelope = m_pageImportSource.SelectedOvfPackage.OvfEnvelope;
                    m_pageNetwork.SelectedOvfEnvelope        = m_pageImportSource.SelectedOvfPackage.OvfEnvelope;

                    NotifyNextPagesOfChange(m_pageEula, m_pageHost, m_pageStorage, m_pageNetwork, m_pageSecurity, m_pageOptions);
                    break;

                case ImportType.Vhd:
                    if (oldTypeOfImport != ImportType.Vhd)
                    {
                        Text = Messages.WIZARD_TEXT_IMPORT_VHD;
                        pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32;
                        RemovePages(appliancePages);
                        RemovePages(xvaPages);
                        AddAfterPage(m_pageImportSource, imagePages);
                    }
                    m_pageVMconfig.IsWim = m_pageImportSource.IsWIM;
                    m_pageHost.SetDefaultTarget(m_pageHost.ChosenItem ?? m_selectedObject);
                    m_pageHost.SelectedOvfEnvelope = null;
                    m_pageHost.VmMappings          = m_vmMappings;
                    NotifyNextPagesOfChange(m_pageVMconfig, m_pageHost, m_pageStorage, m_pageNetwork, m_pageOptions);
                    break;

                case ImportType.Xva:
                    if (oldTypeOfImport != ImportType.Xva)
                    {
                        Text = Messages.WIZARD_TEXT_IMPORT_XVA;
                        pictureBoxWizard.Image = Images.StaticImages._000_ImportVM_h32bit_32;
                        RemovePages(imagePages);
                        RemovePage(m_pageBootOptions);
                        RemovePages(appliancePages);
                        AddAfterPage(m_pageImportSource, xvaPages);
                    }
                    m_pageXvaHost.SetDefaultTarget(m_selectedObject);
                    m_pageXvaStorage.FilePath = m_pageImportSource.FilePath;
                    break;
                }

                #endregion
            }
            else if (type == typeof(ImageVMConfigPage))
            {
                //then use it to create an ovf for the import

                m_envelopeFromVhd = OVF.CreateOvfEnvelope(m_pageVMconfig.VmName,
                                                          m_pageVMconfig.CpuCount, m_pageVMconfig.Memory,
                                                          m_pageBootOptions.BootParams, m_pageBootOptions.PlatformSettings,
                                                          m_pageImportSource.DiskCapacity, m_pageImportSource.IsWIM, m_pageVMconfig.AdditionalSpace,
                                                          m_pageImportSource.FilePath, m_pageImportSource.ImageLength);

                m_pageStorage.SelectedOvfEnvelope        = m_envelopeFromVhd;
                lunPerVdiMappingPage.SelectedOvfEnvelope = m_envelopeFromVhd;
                m_pageNetwork.SelectedOvfEnvelope        = m_envelopeFromVhd;
                ResetVmMappings(m_envelopeFromVhd);
                NotifyNextPagesOfChange(m_pageHost, m_pageStorage, m_pageNetwork);
            }
            else if (type == typeof(ImportSelectHostPage))
            {
                TargetConnection = m_pageHost.ChosenItem == null ? null : m_pageHost.ChosenItem.Connection;
                RemovePage(m_pageRbac);
                ConfigureRbacPage(TargetConnection);
                m_vmMappings             = m_pageHost.VmMappings;
                m_pageStorage.VmMappings = m_vmMappings;
                m_pageStorage.Connection = TargetConnection;
                m_pageNetwork.Connection = TargetConnection;
                m_pageOptions.Connection = TargetConnection;
                RemovePage(m_pageBootOptions);
                if (m_typeOfImport == ImportType.Vhd && BootModesControl.ShowBootModeOptions(TargetConnection))
                {
                    AddAfterPage(m_pageNetwork, m_pageBootOptions);
                    m_pageBootOptions.Connection = TargetConnection;
                }
                m_pageBootOptions.Connection = TargetConnection;
                NotifyNextPagesOfChange(m_pageStorage, m_pageNetwork, m_pageOptions);
            }
            else if (type == typeof(ImportSelectStoragePage))
            {
                RemovePage(lunPerVdiMappingPage);
                lunPerVdiMappingPage.ClearPickerData();
                m_vmMappings                    = m_pageStorage.VmMappings;
                m_pageNetwork.VmMappings        = m_vmMappings;
                lunPerVdiMappingPage.VmMappings = m_vmMappings;
                if (lunPerVdiMappingPage.IsAnyPickerDataMappable &&
                    lunPerVdiMappingPage.MapLunsToVdisRequired &&
                    m_typeOfImport == ImportType.Ovf)
                {
                    AddAfterPage(m_pageStorage, lunPerVdiMappingPage);
                }
            }
            else if (type == typeof(LunPerVdiImportPage))
            {
                m_vmMappings             = lunPerVdiMappingPage.VmMappings;
                m_pageNetwork.VmMappings = m_vmMappings;
            }
            else if (type == typeof(ImportSelectNetworkPage))
            {
                m_vmMappings             = m_pageNetwork.VmMappings;
                m_pageOptions.VmMappings = m_vmMappings;
            }
            else if (type == typeof(GlobalSelectHost))
            {
                var con = m_pageXvaHost.SelectedHost == null ? m_pageXvaHost.SelectedConnection : m_pageXvaHost.SelectedHost.Connection;
                RemovePage(m_pageRbac);
                ConfigureRbacPage(con);

                m_pageXvaStorage.SetConnection(con);
                m_pageXvaStorage.SetTargetHost(m_ignoreAffinitySet ? null : m_pageXvaHost.SelectedHost);

                m_pageXvaNetwork.SetConnection(con);
                m_pageXvaNetwork.SetAffinity(m_pageXvaHost.SelectedHost);

                NotifyNextPagesOfChange(m_pageXvaStorage, m_pageXvaNetwork);
            }
            else if (type == typeof(StoragePickerPage))
            {
                m_pageFinish.ShowStartVmsGroupBox = m_pageXvaStorage.ImportedVm != null && !m_pageXvaStorage.ImportedVm.is_a_template;
                m_pageXvaNetwork.SetVm(m_pageXvaStorage.ImportedVm);
                NotifyNextPagesOfChange(m_pageXvaNetwork);
            }

            if (type != typeof(ImportFinishPage))
            {
                NotifyNextPagesOfChange(m_pageFinish);
            }
        }
Пример #12
0
        private void webclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)             //failure
            {
                Program.Invoke(this, () =>
                {
                    DownloadedPath        = null;
                    m_tlpProgress.Visible = false;
                    var appfile           = (ApplianceFile)e.UserState;
                    ShowDownloadError(string.Format(Messages.IMPORT_DOWNLOAD_ERROR, appfile.RemoteUri, e.Error.Message));
                });
            }
            else if (e.Cancelled)             //user cancelled
            {
                Program.Invoke(this, () =>
                {
                    DownloadedPath = null;
                    DialogResult   = DialogResult.Cancel;
                });
            }
            else             //success
            {
                Program.Invoke(this, () =>
                {
                    var appfile = (ApplianceFile)e.UserState;

                    if (m_filesToDownload.Peek() == appfile)
                    {
                        m_filesToDownload.Dequeue();
                    }

                    if (appfile.LocalPath == DownloadedPath && DownloadedPath.ToLower().EndsWith(".ovf"))
                    {
                        var envType = OVF.Load(DownloadedPath);

                        if (envType != null)
                        {
                            int index     = m_uri.OriginalString.LastIndexOf('/') + 1;
                            var remoteDir = m_uri.OriginalString.Substring(0, index);

                            foreach (var file in envType.References.File)
                            {
                                var remoteUri = new Uri(remoteDir + file.href);
                                var localPath = Path.Combine(m_textBoxWorkspace.Text, file.href);
                                m_filesToDownload.Enqueue(new ApplianceFile(remoteUri, localPath));
                            }
                        }
                    }

                    if (m_filesToDownload.Count == 0)
                    {
                        m_progressBar.Value = 100;
                        DialogResult        = DialogResult.Yes;
                    }
                    else
                    {
                        var file = m_filesToDownload.Peek();
                        m_webClient.DownloadFileAsync(file.RemoteUri, file.LocalPath, file);
                    }
                });
            }
        }
Пример #13
0
 public OvfNetworkResourceContainer(string sysId, EnvelopeType envelopeType)
 {
     rasdArray = OVF.FindRasdByType(envelopeType, sysId, 10);
 }
Пример #14
0
        private void webclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            Program.Invoke(this, () =>
            {
                var appfile = (ApplianceFile)e.UserState;

                if (e.Cancelled)
                {
                    longProcessInProgress = false;
                }
                else if (e.Error != null) // failure
                {
                    progressBar1.Visible  = false;
                    labelProgress.Visible = false;
                    _labelError.Text      = string.Format(Messages.IMPORT_WIZARD_FAILED_DOWNLOAD,
                                                          Path.GetFileName(appfile.LocalPath));
                    m_tlpError.Visible = true;
                    log.Error(string.Format("Failed to download file {0}.", appfile), e.Error);
                    longProcessInProgress = false;
                }
                else // success
                {
                    if (_filesToDownload.Peek() == appfile)
                    {
                        _filesToDownload.Dequeue();
                    }

                    if (appfile.LocalPath.ToLower().EndsWith(".ovf"))
                    {
                        var envType = OVF.Load(appfile.LocalPath);

                        if (envType != null)
                        {
                            int index     = _uri.OriginalString.LastIndexOf('/') + 1;
                            var remoteDir = _uri.OriginalString.Substring(0, index);

                            foreach (var file in envType.References.File)
                            {
                                var remoteUri = new Uri(remoteDir + file.href);
                                var localPath = Path.Combine(_downloadFolder, file.href);
                                _filesToDownload.Enqueue(new ApplianceFile(remoteUri, localPath));
                            }
                        }
                    }

                    if (_filesToDownload.Count == 0)
                    {
                        progressBar1.Value    = 100;
                        progressBar1.Visible  = false;
                        labelProgress.Visible = false;
                        m_textBoxFile.Text    = Path.Combine(_downloadFolder, Path.GetFileName(_uri.AbsolutePath));
                        longProcessInProgress = false;
                    }
                    else
                    {
                        progressBar1.Value = 0;
                        var file           = _filesToDownload.Peek();
                        labelProgress.Text = string.Format(Messages.IMPORT_WIZARD_DOWNLOADING,
                                                           Path.GetFileName(file.LocalPath).Ellipsise(50));
                        _webClient.DownloadFileAsync(file.RemoteUri, file.LocalPath, file);
                    }
                }
            });
        }
Пример #15
0
        private EnvelopeType InitialiseOvfEnvelope()
        {
            EnvelopeType env = OVF.CreateEnvelope(m_pageVMconfig.VmName);

            string systemID        = OVF.AddVirtualSystem(env, m_pageVMconfig.VmName);
            string hdwareSectionId = OVF.AddVirtualHardwareSection(env, systemID);
            string guid            = Guid.NewGuid().ToString();

            OVF.AddVirtualSystemSettingData(env, systemID, hdwareSectionId, env.Name, Messages.VIRTUAL_MACHINE,
                                            Messages.OVF_CREATED, guid, "hvm-3.0-unknown");

            var bootMode = m_pageBootOptions.SelectedBootMode;

            OVF.AddOtherSystemSettingData(env, systemID, "HVM_boot_policy", XenOvf.Properties.Settings.Default.xenBootOptions, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2"));
            var bootParams = XenOvf.Properties.Settings.Default.xenBootParams + (bootMode == BootMode.UEFI_BOOT || bootMode == BootMode.UEFI_SECURE_BOOT ? "firmware=uefi;" : string.Empty);

            OVF.AddOtherSystemSettingData(env, systemID, "HVM_boot_params", bootParams, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_6"));
            var platformSetting = XenOvf.Properties.Settings.Default.xenPlatformSetting + (bootMode == BootMode.UEFI_SECURE_BOOT ? "secureboot=true;" : string.Empty);

            OVF.AddOtherSystemSettingData(env, systemID, "platform", platformSetting, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3"));

            OVF.SetCPUs(env, systemID, m_pageVMconfig.CpuCount);
            OVF.SetMemory(env, systemID, m_pageVMconfig.Memory, "MB");

            string netId = Guid.NewGuid().ToString();

            OVF.AddNetwork(env, systemID, netId, string.Format(Messages.NETWORK_NAME, 0), Messages.OVF_NET_DESCRIPTION, null);

            string diskId   = Guid.NewGuid().ToString();
            ulong  capacity = m_pageImportSource.DiskCapacity;

            if (m_pageImportSource.IsWIM)
            {
                capacity += m_pageVMconfig.AdditionalSpace;
            }
            OVF.AddDisk(env, systemID, diskId, m_pageImportSource.FilePath, true, Messages.OVF_DISK_CAPTION,
                        Messages.OVF_CREATED, m_pageImportSource.ImageLength, capacity);

            OVF.FinalizeEnvelope(env);
            return(env);
        }
Пример #16
0
 public OvfStorageResource(RASD_Type type, EnvelopeType envelopeType)
 {
     rasd     = type;
     envelope = envelopeType;
     file     = OVF.FindFileReferenceByRASD(envelope, rasd);
 }
Пример #17
0
 private void GetFixupIsoInfo()
 {
     m_isoFilename = OVF.GetISOFixupFileName();
 }
Пример #18
0
        private EnvelopeType Export(string targetDir, VM vm, Action <float> updatePercentage)
        {
            if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended)
            {
                log.Error($"Cannot export VM {vm.Name()} ({vm.opaque_ref}); it is neither halted nor suspended.");
                throw new Exception(string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name()));
            }

            log.Info($"Exporting metadata for {vm.name_label}...");

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

            #region TRY TO ID OS

            VM_guest_metrics vmgm = Connection.Resolve(vm.guest_metrics);

            if (vmgm?.os_version != null && vmgm.os_version.TryGetValue("name", out string osName))
            {
                ushort osId = ValueMaps.OperatingSystem(osName);
                if (osId == 0xFFFF)
                {
                    osId = 1; // change to OTHER since search failed.
                }
                string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO");

                if (vmgm.os_version.TryGetValue("major", out string major) &&
                    vmgm.os_version.TryGetValue("minor", out string minor))
                {
                    version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), major, minor);
                }

                string[] osNameParts = osName.Split('|');
                if (osNameParts.Length > 0)
                {
                    OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osNameParts[0], version, osId);
                }
            }

            #endregion

            #region ADD VirtualSystemType identification
            var pv     = vm.IsHVM() ? "hvm" : "xen";
            var arch   = string.IsNullOrEmpty(vm.domarch) ? "unknown" : vm.domarch;
            var vmType = string.Format("{0}-3.0-{1}", pv, arch);

            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 / Util.BINARY_MEGA), "MB");
            #endregion

            #region ADD NETWORKS

            foreach (XenRef <VIF> vifRef in vm.VIFs)
            {
                VIF vif = Connection.Resolve(vifRef);
                if (vif == null)
                {
                    continue;
                }

                XenAPI.Network net = Connection.Resolve(vif.network);
                if (net == null)
                {
                    continue;
                }

                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 EXPORT DISKS

            int diskIndex = 0;
            var vbdRefs   = vm.VBDs;

            for (int i = 0; i < vbdRefs.Count; i++)
            {
                int          curVbd = i;
                XenRef <VBD> vbdRef = vbdRefs[i];

                VBD vbd = Connection.Resolve(vbdRef);
                if (vbd == null)
                {
                    continue;
                }

                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);
                    continue;
                }

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

                try
                {
                    var diskFilename = $"{vdi.uuid}.vhd";
                    var diskPath     = Path.Combine(targetDir, diskFilename);

                    if (File.Exists(diskPath))
                    {
                        var oldFileName = diskFilename;
                        diskFilename = $"{vdi.uuid}_{Thread.CurrentThread.ManagedThreadId}.vhd";
                        diskPath     = Path.Combine(targetDir, diskFilename);
                        log.InfoFormat("VHD Name collision, renamed {0} to {1}", oldFileName, diskFilename);
                    }

                    string diskName = vdi.name_label;
                    if (string.IsNullOrEmpty(diskName))
                    {
                        diskName = $"{OVF.GetContentMessage("RASD_19_CAPTION")} {diskIndex}";
                    }

                    if (!MetaDataOnly)
                    {
                        log.Info($"Exporting disk {diskName} to {diskFilename} for {vm.name_label}...");

                        var taskRef = Task.create(Connection.Session, "export_raw_vdi_task",
                                                  $"Exporting VDI {vdi.uuid} to {diskFilename}");

                        HTTP_actions.get_export_raw_vdi(b =>
                        {
                            Description = string.Format(Messages.EXPORTING_VDI, diskName, diskFilename,
                                                        Util.DiskSizeString(b, 2, "F2"), Util.DiskSizeString(vdi.virtual_size));
                            updatePercentage((curVbd + (float)b / vdi.virtual_size) / vbdRefs.Count);
                        },
                                                        () => Cancelling, XenAdminConfigManager.Provider.GetProxyTimeout(true),
                                                        Connection.Hostname, XenAdminConfigManager.Provider.GetProxyFromSettings(Connection),
                                                        diskPath, taskRef, Connection.Session.opaque_ref, vdi.uuid, "vhd");

                        if (m_shouldVerify)
                        {
                            Description = string.Format(Messages.EXPORTING_VDI_VERIFICATION, diskFilename);

                            using (var stream = new FileStream(diskPath, FileMode.Open, FileAccess.Read))
                                using (var sw = new StringWriter())
                                {
                                    var vhdChecker = new FileChecker(stream);
                                    var result     = vhdChecker.Check(sw, ReportLevels.All);
                                    log.InfoFormat("Verifying disk {0}:\n{1}", diskFilename, sw.ToString().Replace("\0", ""));
                                    if (!result)
                                    {
                                        throw new Exception(string.Format(Messages.EXPORTING_VDI_VERIFICATION_FAILURE, diskFilename));
                                    }
                                }
                        }
                    }

                    string diskId = Guid.NewGuid().ToString();

                    OVF.AddDisk(ovfEnv, vsId, diskId, diskFilename, vbd.bootable, diskName,
                                vdi.name_description, (ulong)vdi.physical_utilisation, (ulong)vdi.virtual_size);
                    OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskId, vbd.userdevice);

                    diskIndex++;
                }
                catch (HTTP.CancelledException)
                {
                    throw new CancelledException();
                }
            }

            #endregion

            #region ADD XEN SPECIFICS

            var _params = vm.HVM_boot_params;
            if (_params != null && _params.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", string.Join(";", _params.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_6"));
            }

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

            var platform = vm.platform;
            if (platform != null && platform.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", string.Join(";", platform.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3"));
            }

            var nvram = vm.NVRAM;
            if (nvram != null && nvram.Count > 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "NVRAM", string.Join(";", nvram.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_7"));
            }

            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.hardware_platform_version >= 0)
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (!string.IsNullOrEmpty(vm.recommendations))
            {
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "recommendations", vm.recommendations.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            if (vm.has_vendor_device)
            {
                //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type
                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1"));
            }

            foreach (XenRef <VGPU> gpuRef in vm.VGPUs)
            {
                VGPU vgpu = Connection.Resolve(gpuRef);

                if (vgpu != null)
                {
                    var vgpuGroup = Connection.Resolve(vgpu.GPU_group);
                    var vgpuType  = Connection.Resolve(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"), true);
                }
            }

            string pvsSiteUuid = string.Empty;
            var    allProxies  = Connection.Cache.PVS_proxies;

            foreach (var p in allProxies.Where(p => p != null && p.VIF != null))
            {
                var vif = Connection.Resolve(p.VIF);
                if (vif != null)
                {
                    var vmFromVif = Connection.Resolve(vif.VM);
                    if (vmFromVif != null && vmFromVif.uuid == vm.uuid)
                    {
                        var pvsSite = Connection.Resolve(p.site);
                        if (pvsSite != null)
                        {
                            pvsSiteUuid = pvsSite.uuid;
                        }

                        break;
                    }
                }
            }

            if (!string.IsNullOrEmpty(pvsSiteUuid))
            {
                var sb = new StringBuilder();
                sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid));

                OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5"));
            }

            #endregion

            OVF.FinalizeEnvelope(ovfEnv);
            return(ovfEnv);
        }