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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                List<XenRef<VDI>> vdiRef = null;

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

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

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

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

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

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

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

                                    string description = "";

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

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

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

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

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

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

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

                        }
                        log.Debug("Import.AddResourceSettingData: Hard Disk Image Added");
                        break;
                        #endregion
                    }
            }
        }
Beispiel #2
0
        private static int compareConnectedDisks(RASD_Type rasd1, RASD_Type rasd2)
        {
            if (rasd1.AddressOnParent != null &&
                rasd1.AddressOnParent.Value != null &&
                rasd2.AddressOnParent != null &&
                rasd2.AddressOnParent.Value != null)
            {

                return (rasd1.AddressOnParent.Value).CompareTo(rasd2.AddressOnParent.Value);
            }
            else
            {
                if (rasd1.Address != null &&
                    rasd1.Address.Value != null &&
                    rasd2.Address != null &&
                    rasd2.Address.Value != null)
                {
                    ushort address1 = Convert.ToUInt16(rasd1.Address.Value);
                    ushort address2 = Convert.ToUInt16(rasd2.Address.Value);
                    return (address1).CompareTo(address2);
                }
                throw new ArgumentNullException("Cannot compare null values");
            }
        }
Beispiel #3
0
 private static int compareControllerRasd(RASD_Type rasd1, RASD_Type rasd2)
 {
     if (rasd1.ResourceType.Value >= 5 &&
         rasd1.ResourceType.Value <= 9 &&
         rasd2.ResourceType.Value >= 5 &&
         rasd2.ResourceType.Value <= 9 &&
         rasd1.Address != null &&
         rasd1.Address.Value != null &&
         rasd2.Address != null &&
         rasd2.Address.Value != null)
     {
         ushort address1 = Convert.ToUInt16(rasd1.Address.Value);
         ushort address2 = Convert.ToUInt16(rasd2.Address.Value);
         int left = (rasd1.ResourceType.Value * 10) + address1;
         int right = (rasd2.ResourceType.Value * 10) + address2;
         return (left).CompareTo(right);
     }
     else
     {
         return rasd1.ResourceType.Value.CompareTo(rasd2.ResourceType.Value);
     }
 }
Beispiel #4
0
 private List<RASD_Type> FindConnectedItems(string instanceId, RASD_Type[] rasds, string value22)
 {
     List<RASD_Type> connectedRasds = new List<RASD_Type>();
     foreach (RASD_Type rasd in rasds)
     {
         if (rasd.Parent != null && !string.IsNullOrEmpty(rasd.Parent.Value) )
         {
             string parent = rasd.Parent.Value.Replace(@"\", "");
             string instance = instanceId.Replace(@"\", "");
             if (parent.Contains(instance))
             {
                 switch (rasd.ResourceType.Value)
                 {
                     case 15:
                     case 16:
                         {
                             connectedRasds.Add(rasd);
                             break;
                         }
                     case 22: // Check to see if it's Microsoft Synthetic Disk Drive
                         {
                             if (Tools.ValidateProperty("ResourceSubType", rasd) &&
                                 rasd.ResourceSubType.Value.ToLower().Contains("synthetic")
                                 )
                             {
                                 connectedRasds.AddRange(FindConnectedItems(rasd.InstanceID.Value, rasds, rasd.Address.Value));
                             }
                             break;
                         }
                     case 17: // VMware Hard Disk
                     case 19: // XenServer/XenConvert Storage Extent
                     case 21: // Microsoft Hard Disk Image
                         {
                             if ((Tools.ValidateProperty("ElementName", rasd) && rasd.ElementName.Value.ToLower().Contains("hard disk")) ||
                                 (Tools.ValidateProperty("Caption", rasd) && rasd.Caption.Value.ToLower().Contains("hard disk")) ||
                                 (Tools.ValidateProperty("Caption", rasd) && rasd.Caption.Value.ToLower().StartsWith("disk"))
                                 )
                             {
                                 if (value22 != null)
                                 {
                                     rasd.Address = new cimString(value22);
                                 }
                                 if (!connectedRasds.Contains(rasd))
                                     connectedRasds.Add(rasd);
                             }
                             break;
                         }
                 }
             }
         }
     }
     Comparison<RASD_Type> diskcomparison = new Comparison<RASD_Type>(compareConnectedDisks);
     connectedRasds.Sort(diskcomparison);
     return connectedRasds;
 }
Beispiel #5
0
        private void SetIfDeviceIsBootable(EnvelopeType ovfEnv, RASD_Type rasd)
        {
            // This is a best guess algorithm. without opening the VHD itself, there is no guarrenteed method
            // to delineate this, so we guess.
            // IF it's created by Kensho/XenConvert there will be a chance of having a clue.
            // Otherwise it'll be based upon 'order' and device 0 will win the bootable device.
            bool isBootable = true;
            VirtualDiskDesc_Type[] disks = null;

            foreach (Section_Type sect in ovfEnv.Sections)
            {
                if (sect is DiskSection_Type)
                {
                    disks = ((DiskSection_Type)sect).Disk;
                }
            }

            if (disks == null)
                return;

            bool useHostResource = false;
            if (Tools.ValidateProperty("HostResource", rasd))
            {
                log.Debug("Using HostResource to find Disk");
                useHostResource = true;
            }
            else
            {
                log.Debug("Using InstanceID to find Disk");
            }

            foreach(VirtualDiskDesc_Type disk in disks)
            {
                if (useHostResource)
                {
                    if (rasd.HostResource[0].Value.Contains(disk.diskId))
                    {
                        isBootable = disk.isBootable;
                    }
                }
                else
                {
                    if (rasd.InstanceID.Value.Contains(disk.diskId))
                    {
                        isBootable = disk.isBootable;
                    }
                }
            }

            if (Tools.ValidateProperty("Address", rasd))
            {
                if ((rasd.ResourceType.Value == 21 ||
                    rasd.ResourceType.Value == 5) &&
                    rasd.Address.Value == "0")
                {
                    isBootable = true;
                }
            }

            if (Tools.ValidateProperty("AddressOnParent", rasd))
            {
                if ((rasd.ResourceType.Value == 17 ||
                    rasd.ResourceType.Value == 19) &&
                    rasd.AddressOnParent.Value == "0")
                {
                    isBootable = true;
                }
            }

            if (Tools.ValidateProperty("Connection", rasd))
            {
                if (rasd.Connection[0].Value.Contains("device=0"))
                {
                    isBootable = true;
                }
                if (!rasd.Connection[0].Value.Contains("bootable"))
                {
                    rasd.Connection[0].Value = string.Format("{0},bootable={1}", rasd.Connection[0].Value, isBootable);
                }
            }
            else
            {
                rasd.Connection = new cimString[] { new cimString(string.Format("bootable={0}", isBootable)) };
            }
        }
Beispiel #6
0
 public OvfStorageResource(RASD_Type type, EnvelopeType envelopeType)
 {
     rasd = type;
     envelope = envelopeType;
     file = OVF.FindFileReferenceByRASD(envelope, rasd);
 }
 public OvfNetworkResource(RASD_Type rasdType)
 {
     rasd = rasdType;
 }
Beispiel #8
0
        private EnvelopeType ConvertFromHyperVXml(Ms_Declarations_Type hvobj, string ovfname, string lang)
        {
            EnvelopeType env = CreateEnvelope(ovfname, lang);
            string systemId = AddVirtualSystem(env, lang, ovfname);
            string vhsid = AddVirtualHardwareSection(env, systemId, lang);

            foreach (Ms_WrapperInstance_Type wrap in hvobj.declgroups[0].values)
            {
                RASD_Type rasd = new RASD_Type();
                switch (wrap.instance.className)
                {
                    #region CASE: Msvm_VirtualSystemSettingData
                    case "Msvm_VirtualSystemSettingData":
                        {
                            string ElementName = null;
                            string InstanceId = null;
                            string SystemName = null;
                            string VirtualSystemType = null;
                            foreach (Ms_Property_Base_Type prop in wrap.instance.Properties)
                            {
                                switch (prop.Name)
                                {
                                    case "ElementName":
                                        {
                                            ElementName = ((Ms_ParameterValue_Type)prop).Value;
                                            break;
                                        }
                                    case "InstanceID":
                                        {
                                            InstanceId = ((Ms_ParameterValue_Type)prop).Value;
                                            break;
                                        }
                                    case "SystemName":
                                        {
                                            SystemName = ((Ms_ParameterValue_Type)prop).Value;
                                            break;
                                        }
                                    case "VirtualSystemType":
                                        {
                                            VirtualSystemType = ((Ms_ParameterValue_Type)prop).Value;
                                            break;
                                        }
                                }
                            }
                            AddVirtualSystemSettingData(env, systemId, vhsid, ElementName, ElementName, ElementName, InstanceId, VirtualSystemType);
                            UpdateVirtualSystemName(env, systemId, lang, ElementName);
                            break;
                        }
                    #endregion

                    #region CASE: ResourceAllocationSettingData
                    case "Msvm_ProcessorSettingData":
                    case "Msvm_MemorySettingData":
                    case "Msvm_SyntheticEthernetPortSettingData":
                    case "Msvm_ResourceAllocationSettingData":
                        {
                            foreach (Ms_Property_Base_Type prop in wrap.instance.Properties)
                            {
                                if (prop is Ms_ParameterValue_Type)
                                {
                                  if (((Ms_ParameterValue_Type)prop).Value == null ||
                                     ((Ms_ParameterValue_Type)prop).Value.Length <= 0)
                                     {
                                         continue;
                                     }
                                }
                                else if (prop is Ms_ParameterValueArray_Type)
                                {
                                    if  (((Ms_ParameterValueArray_Type)prop).Values == null ||
                                        ((Ms_ParameterValueArray_Type)prop).Values.Length <= 0)
                                    {
                                        continue;
                                    }
                                }

                                PropertyInfo[] properties = rasd.GetType().GetProperties();
                                foreach (PropertyInfo pi in properties)
                                {
                                    if (pi.Name.ToLower().Equals(prop.Name.ToLower()))
                                    {
                                        object newvalue = null;
                                        if (prop is Ms_ParameterValue_Type)
                                        {
                                            switch (prop.Type.ToLower())
                                            {
                                                case "string":
                                                    {
                                                        newvalue = new cimString((string)((Ms_ParameterValue_Type)prop).Value);
                                                        break;
                                                    }
                                                case "boolean":
                                                    {
                                                        newvalue = new cimBoolean();
                                                        ((cimBoolean)newvalue).Value = Convert.ToBoolean(((Ms_ParameterValue_Type)prop).Value);
                                                        break;
                                                    }
                                                case "uint16":
                                                    {
                                                        newvalue = new cimUnsignedShort();
                                                        ((cimUnsignedShort)newvalue).Value = Convert.ToUInt16(((Ms_ParameterValue_Type)prop).Value);
                                                        break;
                                                    }
                                                case "uint32":
                                                    {
                                                        newvalue = new cimUnsignedInt();
                                                        ((cimUnsignedInt)newvalue).Value = Convert.ToUInt32(((Ms_ParameterValue_Type)prop).Value);
                                                        break;
                                                    }
                                                case "uint64":
                                                    {
                                                        newvalue = new cimUnsignedLong();
                                                        ((cimUnsignedLong)newvalue).Value = Convert.ToUInt64(((Ms_ParameterValue_Type)prop).Value);
                                                        break;
                                                    }
                                            }
                                        }
                                        else if (prop is Ms_ParameterValueArray_Type)
                                        {
                                            switch (prop.Type.ToLower())
                                            {
                                                case "string":
                                                    {
                                                        List<cimString> sarray = new List<cimString>();
                                                        foreach (Ms_ParameterValue_Type svalue in ((Ms_ParameterValueArray_Type)prop).Values)
                                                        {
                                                            sarray.Add(new cimString(svalue.Value));
                                                        }
                                                        newvalue = sarray.ToArray();
                                                        break;
                                                    }
                                            }
                                        }

                                        object tmpobject = null;
                                        switch (pi.Name.ToLower())
                                        {
                                            case "caption":
                                                {
                                                    newvalue = new Caption(((cimString)newvalue).Value);
                                                    break;
                                                }
                                            case "changeabletype":
                                                {
                                                    tmpobject = newvalue;
                                                    newvalue = new ChangeableType();
                                                    ((ChangeableType)newvalue).Value = ((cimUnsignedShort)tmpobject).Value;
                                                    break;
                                                }
                                            case "consumervisibility":
                                                {
                                                    tmpobject = newvalue;
                                                    newvalue = new ConsumerVisibility();
                                                    ((ConsumerVisibility)newvalue).Value = ((cimUnsignedShort)tmpobject).Value;
                                                    break;
                                                }
                                            case "mappingbehavior":
                                                {
                                                    tmpobject = newvalue;
                                                    newvalue = new MappingBehavior();
                                                    ((MappingBehavior)newvalue).Value = ((cimUnsignedShort)tmpobject).Value;
                                                    break;
                                                }
                                            case "resourcetype":
                                                {
                                                    tmpobject = newvalue;
                                                    newvalue = new ResourceType();
                                                    ((ResourceType)newvalue).Value = ((cimUnsignedShort)tmpobject).Value;
                                                    break;
                                                }
                                            case "connection":
                                            case "hostresource":
                                            default:
                                                {
                                                    break;
                                                }

                                        }
                                        pi.SetValue(rasd, newvalue, null);
                                    }
                                }
                            }
                            if (rasd != null)
                            {
                                if (FillEmptyRequiredFields(rasd))
                                {
                                    if (rasd.ResourceType.Value == 21 &&
                                        rasd.Caption.Value.ToLower().StartsWith(_ovfrm.GetString("RASD_19_CAPTION").ToLower()))
                                    {
                                        string filename = Path.GetFileName(rasd.Connection[0].Value);
                                        AddFileReference(env, lang, filename, rasd.InstanceID.Value, 0, Properties.Settings.Default.winFileFormatURI);
                                        AddRasd(env, systemId, rasd);
                                    }
                                    else if (rasd.ResourceType.Value == 10)
                                    {
                                        AddNetwork(env, systemId, lang, rasd.InstanceID.Value, rasd.Caption.Value, rasd.Address.Value);
                                    }
                                    else
                                    {
                                        AddRasd(env, systemId, rasd);
                                    }
                                }
                            }
                            break;
                        }
                    #endregion

                    #region CASE: Msvm_VLANEndpointSettingData
                    case "Msvm_VLANEndpointSettingData":
                    #endregion

                    #region CASE: SKIPPED / DEFAULT
                    case "Msvm_VirtualSystemExportSettingData":
                    case "Msvm_VirtualSystemGlobalSettingData":
                    case "Msvm_HeartbeatComponentSettingData":
                    case "Msvm_KvpExchangeComponentSettingData":
                    case "Msvm_ShutdownComponentSettingData":
                    case "Msvm_TimeSyncComponentSettingData":
                    case "Msvm_VssComponentSettingData":
                    case "Msvm_SwitchPort":
                    case "Msvm_VirtualSwitch":
                    default:
                        {
                            break;
                        }
                    #endregion
                }
            }

            FinalizeEnvelope(env);
            return env;
        }
Beispiel #9
0
        /// <summary>
        /// An ovf can contain both encrypted and non-encrypted file mixed together.
        /// find if file name is encrypted.
        /// 1. check the References for the security ID
        /// 2. check the Security id section exists.
        /// </summary>
        /// <param name="ovfObj">OVF Envelope</param>
        /// <param name="filename">filename to check</param>
        /// <returns>true = encrypted; false = not encrypted</returns>
        public static bool IsThisEncrypted(EnvelopeType ovfObj, RASD_Type rasd)
        {
            bool _isEncrypted = false;
            // 15,16,17,19,20 are attached files.
            // rest is RASD specific

            switch (rasd.ResourceType.Value)
            {
                case 15:
                case 16:
                case 17:
                case 19:
                case 20:
                    {
                        File_Type file = FindFileReferenceByRASD(ovfObj, rasd);
                        if (file != null)
                        {
                            if (!string.IsNullOrEmpty(file.Id))
                            {
                                _isEncrypted = IsThisIdEncrypted(ovfObj, file.Id);
                            }
                        }
                        break;
                    }
                default:
                    {
                        // currently encrypted RASD or Elements, isn't being done, but this can check it.
                        if (rasd.AnyAttr != null && rasd.AnyAttr.Length > 0)
                        {
                            foreach (XmlAttribute xa in rasd.AnyAttr)
                            {
                                if (xa.Name.ToLower().Equals("xenc:id"))
                                {
                                    _isEncrypted = IsThisIdEncrypted(ovfObj, xa.Value);
                                    break;
                                }
                            }
                        }
                        break;
                    }
            }
            return _isEncrypted;
        }
Beispiel #10
0
 private static bool ValidateNetworks(NetworkSection_TypeNetwork[] networks, RASD_Type[] rasds, ValidationFlags validationFlags, ref List<string> validationErrorMessages)
 {
     bool isValid = true;
     if ((validationFlags & ValidationFlags.Networks) != 0)
     {
         foreach (RASD_Type rasd in rasds)
         {
             if (rasd.ResourceType.Value == 10)
             {
                 bool linkage = false;
                 if (rasd.InstanceID == null || rasd.InstanceID.Value.Length <= 0)
                 {
                     log.Info("Network has an invalid InstanceID, creating new.");
                     validationErrorMessages.Add(Messages.VALIDATION_INVALID_INSTANCEID);
                     rasd.InstanceID = new cimString(Guid.NewGuid().ToString());
                     break;
                 }
                 foreach (NetworkSection_TypeNetwork net in networks)
                 {
                     //
                     // this may only work for Citrix Created VOFs
                     // haven't looked at others, may need to use a different key to validate linkage.
                     //
                     if ((rasd.Connection != null && rasd.Connection.Length > 0 &&
                          net.name == rasd.Connection[0].Value) ||
                         (net.Description.msgid == rasd.InstanceID.Value))
                     {
                         linkage = true;
                     }
                 }
                 if (!linkage)
                 {
                     log.Error(Messages.VALIDATION_NETWORK_NO_DEVICE);
                     validationErrorMessages.Add(Messages.VALIDATION_NETWORK_NO_DEVICE);
                     isValid = false;
                     break;
                 }
             }
         }
     }
     return isValid;
 }
Beispiel #11
0
 private static bool ValidateMemory(RASD_Type[] rasds, ValidationFlags validationFlags, ref List<string> validationErrorMessages)
 {
     bool isValid = true;
     if ((validationFlags & ValidationFlags.Memory) != 0)
     {
         foreach (RASD_Type rasd in rasds)
         {
             if (rasd.ResourceType.Value == 4)
             {
                 if (rasd.VirtualQuantity == null || rasd.VirtualQuantity.Value <= 0)
                 {
                     log.Error("Memory invalid Virtual Quantity");
                     validationErrorMessages.Add(Messages.VALIDATION_INVALID_MEMORY_QUANTITY);
                     isValid = false;
                     break;
                 }
                 if (rasd.AllocationUnits == null || rasd.AllocationUnits.Value.Length <= 0)
                 {
                     log.Error("Memory AllocationUnits not valid");
                     validationErrorMessages.Add(Messages.VALIDATION_INVALID_MEMORY_ALLOCATIONUNITS);
                     isValid = false;
                     break;
                 }
                 if (rasd.InstanceID == null || rasd.InstanceID.Value.Length <= 0)
                 {
                     log.Info("Memory has an invalid InstanceID, creating new.");
                     validationErrorMessages.Add(Messages.VALIDATION_INVALID_INSTANCEID);
                     rasd.InstanceID = new cimString(Guid.NewGuid().ToString());
                     break;
                 }
             }
         }
     }
     return isValid;
 }
Beispiel #12
0
        private static bool ValidateFiles(string ovfpath, File_Type[] files, VirtualDiskDesc_Type[] disks, RASD_Type[] rasds, ValidationFlags validationFlags, ref List<string> validationErrorMessages)
        {
            bool isValid = true;
            if ((validationFlags & ValidationFlags.Files) != 0)
            {
                if (files != null && files.Length > 0)
                {
                    foreach (File_Type file in files)
                    {
                        string ext = Path.GetExtension(file.href).ToLower();
                        if (ext == Properties.Settings.Default.manifestFileExtension || ext == Properties.Settings.Default.certificateFileExtension)
                            continue;

                        string filename = string.Format(@"{0}{1}{2}", string.IsNullOrEmpty(ovfpath) ? "" : ovfpath,
                                                                      string.IsNullOrEmpty(ovfpath) ? "" : @"\",
                                                                      file.href);
                        if (!File.Exists(filename))
                        {
                            var message = string.Format(Messages.VALIDATION_FILE_NOTFOUND, file.href);
                            validationErrorMessages.Add(message);
                            log.Error(message);
                            throw new Exception(message);
                        }
                    }
                }
                else
                {
                    log.Info("ValidateFiles: no attached files defined, continuing");
                    return isValid;
                }
                if (isValid)
                {
                    bool validlink = false;
                    foreach (File_Type file in files)
                    {
                        validlink = false;
                        foreach (VirtualDiskDesc_Type disk in disks)
                        {
                            if (file.id == disk.fileRef)
                            {
                                foreach (RASD_Type rasd in rasds)
                                {
                                    if (rasd.ResourceType.Value == 17 ||
                                        rasd.ResourceType.Value == 19 ||
                                        rasd.ResourceType.Value == 20 ||
                                        rasd.ResourceType.Value == 21)
                                    {
                                        if (rasd.HostResource != null && rasd.HostResource.Length > 0)
                                        {
                                            if (rasd.HostResource[0].Value.Contains(disk.diskId))
                                            {
                                                validlink = true;
                                                break;
                                            }
                                        }
                                        else if (disk.diskId == rasd.InstanceID.Value)
                                        {
                                            validlink = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (!validlink)
                        {
                            log.WarnFormat("Disk linkage [File to RASD] does not exist: {0}", file.href);
                            break;
                        }
                    }
                }
            }
            return isValid;
        }
Beispiel #13
0
 private static bool ValidateCpu(RASD_Type[] rasds, ValidationFlags validationFlags, ref List<string> validationErrorMessages)
 {
     bool isValid = true;
     if ((validationFlags & ValidationFlags.Cpu) != 0)
     {
         foreach (RASD_Type rasd in rasds)
         {
             if (rasd.ResourceType.Value == 3)
             {
                 if (rasd.VirtualQuantity == null || rasd.VirtualQuantity.Value <= 0)
                 {
                     var message = string.Format(Messages.VALIDATION_INVALID_CPU_QUANTITY, rasd.VirtualQuantity.Value);
                     log.Error(message);
                     validationErrorMessages.Add(message);
                     break;
                 }
                 if (rasd.Limit != null && rasd.VirtualQuantity.Value > rasd.Limit.Value)
                 {
                     var message = string.Format(Messages.VALIDATION_INVALID_CPU_EXCEEDS_LIMIT, rasd.VirtualQuantity.Value, rasd.Limit.Value);
                     log.Error(message);
                     validationErrorMessages.Add(message);
                     isValid = false;
                     break;
                 }
                 if (rasd.InstanceID == null || rasd.InstanceID.Value.Length <= 0)
                 {
                     log.Info("CPU has an invalid InstanceID, creating new.");
                     validationErrorMessages.Add(Messages.VALIDATION_INVALID_INSTANCEID);
                     rasd.InstanceID = new cimString(Guid.NewGuid().ToString());
                     break;
                 }
             }
         }
     }
     return isValid;
 }
Beispiel #14
0
 private static bool ValidateCapability(RASD_Type[] rasds, ValidationFlags validationFlags, ref List<string> validationErrorMessages)
 {
     bool isValid = true;
     if ((validationFlags & ValidationFlags.Capability) != 0)
     {
         foreach (RASD_Type rasd in rasds)
         {
             switch (rasd.ResourceType.Value)
             {
                 // CIM SCHEMA 2.19.0
                 case 3:  // Processor
                 case 4:  // Memory
                 case 5:  // IDE Controller
                 case 6:  // Parallel SCSI HBA
                 case 7:  // FC HBA
                 case 8:  // iSCSI HBA
                 case 9:  // IB HCA
                 case 10: // Ehternet Adapter
                 case 15: // CD Drive
                 case 16: // DVD Drive
                 case 17: // Disk Drive
                 case 19: // Storage Extent
                 case 20: // Other storage Device
                 case 21: // Serial Port  // Microsoft uses this for Hard Disk Image also, based on an OLDER schema
                     {
                         if (rasd.required)
                         {
                             isValid = true;
                         }
                         break;
                     }
                 case 1:  // Other
                 case 2:  // Computer System
                 case 11: // Other Network Adapter
                 case 12: // I/O Slot
                 case 13: // I/O Device
                 case 14: // Floppy Drive
                 case 18: // Tape Drive
                 case 22: // Parallel Port
                 case 23: // USB Controller
                 case 24: // Graphics Controller
                 case 25: // IEEE 1394 Controller
                 case 26: // Partitionable Unit
                 case 27: // Base Partitionable Unit
                 case 28: // Power
                 case 29: // Cooling Capacity
                 case 30: // Ethernet Switch Port
                 case 31: // Logical Disk
                 case 32: // Storage Volume
                 case 33: // Ethernet Connection
                 default:
                     {
                         if (rasd.required)
                         {
                             var message = string.Format(Messages.VALIDATION_REQUIRED_ELEMENT_NOT_RECOGNIZED, rasd.ResourceType.Value, rasd.ElementName.Value);
                             log.Error(message);
                             validationErrorMessages.Add(message);
                             isValid = false;
                         }
                         break;
                     }
             }
             if (!isValid)
                 break;
         }
     }
     return isValid;
 }