예제 #1
0
 public EvacuateHostPlanAction(Host host)
     : base(host.Connection, string.Format(Messages.PLANACTION_VMS_MIGRATING, host.Name))
 {
     base.TitlePlan = string.Format(Messages.MIGRATE_VMS_OFF_SERVER, host.Name);
     this._host = new XenRef<Host>(host);
     currentHost = host;
 }
예제 #2
0
        protected override void Run()
        {
            try
            {
                Description = string.Format(Messages.ARCHIVING_SNAPSHOT_X, _snapshot.Name);
                RelatedTask=new XenRef<Task>(VMPP.archive_now(Session, _snapshot.opaque_ref));
                PollToCompletion();
                Description = string.Format(Messages.ARCHIVED_SNAPSHOT_X, _snapshot.Name);
            }
            catch (Exception e)
            {
                Failure f = e as Failure;
                if (f != null)
                {
                    string msg = "";
                    if (f.ErrorDescription.Count > 3)
                    {
                        msg = XenAPI.Message.FriendlyName(f.ErrorDescription[3]);
                    }

                    throw new Exception(msg);

                }
                throw;
            }
        }
 public BringBabiesBackAction(List<XenRef<VM>> vms, Host host,bool enableOnly)
     : base(host.Connection, string.Format(Messages.UPDATES_WIZARD_EXITING_MAINTENANCE_MODE,host.Name))
 {
     base.TitlePlan = string.Format(Messages.EXIT_SERVER_FROM_MAINTENANCE_MODE,host.Name);
     this._host = new XenRef<Host>(host);
     this._vms = vms;
     this._enableOnly = enableOnly;
     currentHost = host;
 }
예제 #4
0
 public MeddlingAction(Task task)
     : base(ActionType.Meddling, task.MeddlingActionTitle ?? task.Title, task.Description, false, false)
 {
     RelatedTask = new XenRef<Task>(task.opaque_ref);
     Started = (task.created + task.Connection.ServerTimeOffset).ToLocalTime();
     SetAppliesToData(task);
     VM = VMFromAppliesTo(task);
     Connection = task.Connection;
     Update(task, false);
 }
예제 #5
0
 protected override void Run()
 {
     Description = string.Format(Messages.CREATING_VM_APPLIANCE, _record.Name);
     RelatedTask = VM_appliance.async_create(Session, _record);
     PollToCompletion();
     var vmApplianceRef = new XenRef<VM_appliance>(Result);
     Connection.WaitForCache(vmApplianceRef);
     foreach (var selectedVM in _vms)
     {
         VM.set_appliance(Session, selectedVM.opaque_ref, vmApplianceRef.opaque_ref);
     }
     Description = string.Format(Messages.CREATED_VM_APPLIANCE, _record.Name);
     PercentComplete = 100;
 }
예제 #6
0
        public MeddlingAction(Task task)
            : base(task.MeddlingActionTitle ?? task.Title, task.Description, false, false)
        {
            RelatedTask = new XenRef<Task>(task.opaque_ref);

            this.Host = task.Connection.Resolve(task.resident_on);

            if (this.Host == null)
                this.Host = Helpers.GetMaster(task.Connection);

            Started = (task.created + task.Connection.ServerTimeOffset).ToLocalTime();
            SetAppliesToData(task);
            VM = VMFromAppliesTo(task);
            Connection = task.Connection;
            Update(task, false);
        }
예제 #7
0
 protected override void Run()
 {
     Description = string.Format(Messages.CREATING_VMPP, _record.Name);
     RelatedTask = VMPP.async_create(Session, _record);
     PollToCompletion();
     var vmppref = new XenRef<VMPP>(Result);
     Connection.WaitForCache(vmppref);
     foreach (var selectedVM in _vms)
     {
         VM.set_protection_policy(Session, selectedVM.opaque_ref, vmppref.opaque_ref);
     }
     Description = string.Format(Messages.CREATED_VMPP, _record.Name);
     PercentComplete = 60;
     if (_runNow)
         VMPP.protect_now(Session, vmppref);
     PercentComplete = 100;
 }
예제 #8
0
        public CreateSingleVM(Session session, string hostUuid)
        {
            this.session = session;
            this.hostUuid = hostUuid;

            this.hostRef = Host.get_by_uuid(session, hostUuid);

            try
            {
                this.version = Host.call_plugin(session, this.hostRef, "skinnybox", "version", null);
            }
            catch (Exception e)
            {
                MessageBox.Show("Unable to contact the skinnybox plugin. Please make sure that skinnybox exists in /etc/xapi.d/plugins/ and has execute permissions.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            InitializeComponent();
        }
예제 #9
0
        /// <summary>
        /// A general HttpPut method, with delegates for progress and cancelling
        /// </summary>
        /// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param>
        /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
        /// <param name="timeout">Timeout value in ms</param>
        /// <param name="task">The task used to track this http get</param>
        /// <param name="session">Session used to make api calls (may be replaced if logged out, hence ref)</param>
        /// <param name="path">Path to file to put</param>
        /// <returns>The result of the task passed in</returns>
        public static String Put(XenAPI.HTTP.UpdateProgressDelegate progressDelegate, HTTP.FuncBool cancellingDelegate, int timeout,
            IXenConnection connection, XenRef<Task> task, ref Session session, string path,
            string hostname, Delegate f, params object[] p)
        {
            log.DebugFormat("HTTP PUTTING file from {0} to {1}", path, hostname);

            HTTP.FuncBool cancellingDelegate2 = (HTTP.FuncBool)delegate()
            {
                return (XenAdminConfigManager.Provider.ForcedExiting ||
                    cancellingDelegate != null && cancellingDelegate());
            };

            try
            {
                List<object> args = new List<object>();
                args.Add(progressDelegate);
                args.Add(cancellingDelegate2);
                args.Add(timeout);
                args.Add(hostname);
                args.Add(XenAdminConfigManager.Provider.GetProxyFromSettings(connection));
                args.Add(path);
                args.Add(task.opaque_ref);  // task_id
                args.AddRange(p);
                f.DynamicInvoke(args.ToArray());
            }
            catch (Exception e)
            {
                log.DebugFormat("Caught exception doing HTTP PUT from {0} to {1}", path, hostname);
                log.Debug(e, e);
                PollTaskForResult(connection, ref session, cancellingDelegate2, task, true);
                if (e is CancelledException || e.InnerException is CancelledException)
                    throw new XenAdmin.CancelledException();
                else
                    throw;
            }

            return PollTaskForResult(connection, ref session, cancellingDelegate2, task);
        }
예제 #10
0
        public static String Get(HTTP.UpdateProgressDelegate progressDelegate, HTTP.FuncBool cancellingDelegate, bool timeout,
            HTTP.DataCopiedDelegate dataRxDelegate, IXenConnection connection, XenRef<Task> task, ref Session session, string path,
            string hostname, Delegate f, params object[] p)
        {
            log.DebugFormat("HTTP GETTING file from {0} to {1}", hostname, path);

            // Cannot use ref param in anonymous method, so save it here and restore it later
            Session _session = session;

            HTTP.DataCopiedDelegate dataCopiedDelegate = delegate(long bytes)
            {
                if (progressDelegate != null)
                {
                    int progress = (int)(100 * (double)Task.DoWithSessionRetry(connection, ref _session,
                        (Task.TaskProgressOp)Task.get_progress, task.opaque_ref));

                    progressDelegate(progress);
                }

                if (dataRxDelegate != null)
                    dataRxDelegate(bytes);
            };

            HTTP.FuncBool cancellingDelegate2 = (HTTP.FuncBool)delegate()
            {
                return (XenAdminConfigManager.Provider.ForcedExiting ||
                    cancellingDelegate != null && cancellingDelegate());
            };

            try
            {
                List<object> args = new List<object>();
                args.Add(dataCopiedDelegate);
                args.Add(cancellingDelegate2);
                args.Add(XenAdminConfigManager.Provider.GetProxyTimeout(timeout));
                args.Add(hostname);
                args.Add(XenAdminConfigManager.Provider.GetProxyFromSettings(connection));
                args.Add(path);
                args.Add(task.opaque_ref);  // task_id
                args.AddRange(p);
                f.DynamicInvoke(args.ToArray());
            }
            catch (Exception e)
            {
                log.DebugFormat("Caught exception doing HTTP GET from {0} to {1}", hostname, path);
                log.Debug(e, e);

                if (e is WebException && e.InnerException is IOException && Win32.GetHResult(e.InnerException as IOException) == Win32.ERROR_DISK_FULL)
                    throw e.InnerException;
                else if (e is CancelledException || e.InnerException is CancelledException)
                    throw new XenAdmin.CancelledException();
                else if (e.InnerException.Message == "Received error code HTTP/1.1 403 Forbidden\r\n from the server")
                {
                    // RBAC Failure
                    List<Role> roles = connection.Session.Roles;
                    roles.Sort();
                    throw new Exception(String.Format(Messages.RBAC_HTTP_FAILURE, roles[0].FriendlyName), e);
                }
                else
                    throw e.InnerException;
            }

            return PollTaskForResult(connection, ref session, cancellingDelegate2, task);
        }
예제 #11
0
 /// <summary>
 /// A general HttpPut method, with delegates for progress and cancelling
 /// </summary>
 /// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param>
 /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param>
 /// <param name="timeout">Whether to apply a timeout</param>
 /// <param name="task">The task used to track this http get</param>
 /// <param name="session">Session used to make api calls (may be replaced if logged out, hence ref)</param>
 /// <param name="path">Path to file to put</param>
 /// <returns>The result of the task passed in</returns>
 public static String Put(XenAPI.HTTP.UpdateProgressDelegate progressDelegate, HTTP.FuncBool cancellingDelegate, bool timeout,
     IXenConnection connection, XenRef<Task> task, ref Session session, string path,
     string hostname, Delegate f, params object[] p)
 {
     return Put(progressDelegate, cancellingDelegate, XenAdminConfigManager.Provider.GetProxyTimeout(timeout),
                connection, task, ref session, path, hostname, f, p);
 }
예제 #12
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
                    }
            }
        }
예제 #13
0
 public AutoStartEnabled(Check check, VM vm)
     : base(check)
 {
     _VMref      = new XenRef <VM>(vm);
     _connection = vm.Connection;
 }
예제 #14
0
        protected override void Run()
        {
            log.DebugFormat("Running SrActionKind.{0}", kind.ToString());

            int inc = SR.PBDs.Count > 0 ? 100 / (SR.PBDs.Count * 2) : 0;

            switch (kind)
            {
            case SrActionKind.Detach:
                UnplugPBDs(ref inc);
                Description = string.Format(Messages.ACTION_SR_DETACH_SUCCESSFUL, SR.NameWithoutHost);
                break;

            case SrActionKind.Destroy:
                RelatedTask = XenAPI.SR.async_destroy(Session, SR.opaque_ref);
                PollToCompletion(50, 100);
                Description = Messages.ACTION_SR_DESTROY_SUCCESSFUL;
                break;

            case SrActionKind.Forget:
                Description = string.Format(Messages.FORGETTING_SR_0, SR.NameWithoutHost);
                if (!SR.allowed_operations.Contains(storage_operations.forget))
                {
                    Description = Messages.ERROR_DIALOG_FORGET_SR_TITLE;
                    break;
                }

                RelatedTask = XenAPI.SR.async_forget(Session, SR.opaque_ref);
                PollToCompletion();
                Description = string.Format(Messages.SR_FORGOTTEN_0, SR.NameWithoutHost);
                break;

            case SrActionKind.SetAsDefault:
                XenRef <SR> r = new XenRef <SR>(SR);
                Pool        = Helpers.GetPoolOfOne(Connection);
                Description = string.Format(Messages.ACTION_SR_SETTING_DEFAULT, SR, Pool);
                Pool poolCopy = (Pool)Pool.Clone();
                if (Pool != null)
                {
                    poolCopy.crash_dump_SR    = r;
                    poolCopy.default_SR       = r;
                    poolCopy.suspend_image_SR = r;
                    try
                    {
                        Pool.Locked = true;
                        poolCopy.SaveChanges(Session);
                    }
                    finally
                    {
                        Pool.Locked = false;
                    }
                }

                Description = Messages.ACTION_SR_SET_DEFAULT_SUCCESSFUL;
                break;

            case SrActionKind.UnplugAndDestroyPBDs:
                UnplugPBDs(ref inc);
                DestroyPBDs(ref inc);
                Description = string.Format(Messages.ACTION_SR_DETACH_SUCCESSFUL, SR.NameWithoutHost);
                break;
            }
        }
예제 #15
0
        public void Process(Session xenSession, EnvelopeType ovfObj, string pathToOvf, string passcode)
        {
            if (xenSession == null)
                throw new InvalidOperationException(Messages.ERROR_NOT_CONNECTED);

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

            vifDeviceIndex = 0;
            string encryptionVersion = null;

            #region CHECK ENCRYPTION
            if (OVF.HasEncryption(ovfObj))
            {
                if (passcode == null)
                {
                    throw new InvalidDataException(Messages.ERROR_NO_PASSWORD);
                }
                string fileuuids = null;
                SecuritySection_Type[] securitysection = OVF.FindSections<SecuritySection_Type>((ovfObj).Sections);
                if (securitysection != null && securitysection.Length >= 0)
                {
                    foreach (Security_Type securitytype in securitysection[0].Security)
                    {
                        if (securitytype.ReferenceList.Items != null && securitytype.ReferenceList.Items.Length > 0)
                        {
                            foreach (XenOvf.Definitions.XENC.ReferenceType dataref in securitytype.ReferenceList.Items)
                            {
                                if (dataref is DataReference)
                                {
                                    fileuuids += ":" + ((DataReference)dataref).ValueType;
                                }
                            }
                        }
                        if (securitytype.EncryptionMethod != null && securitytype.EncryptionMethod.Algorithm != null)
                        {
                            string algoname = (securitytype.EncryptionMethod.Algorithm.Split(new char[] { '#' }))[1].ToLower().Replace('-', '_');
                            object x = OVF.AlgorithmMap(algoname);
                            if (x != null)
                            {
                                EncryptionClass = (string)x;
                                EncryptionKeySize = Convert.ToInt32(securitytype.EncryptionMethod.KeySize);
                            }
                        }

                        if (!string.IsNullOrEmpty(securitytype.version))
                        {
                            encryptionVersion = securitytype.version;
                        }
                    }
                }
            }
            #endregion

            #region FIND DEFAULT SR
            Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(xenSession);
            foreach (XenRef<Pool> pool in pools.Keys)
            {
                DefaultSRUUID = pools[pool].default_SR;
                break;
            }
            #endregion

            //
            // So the process is the same below, change this
            //
            if (ovfObj.Item is VirtualSystem_Type)
            {
                VirtualSystem_Type vstemp = (VirtualSystem_Type)ovfObj.Item;
                ovfObj.Item = new VirtualSystemCollection_Type();
                ((VirtualSystemCollection_Type)ovfObj.Item).Content = new Content_Type[] { vstemp };
            }

            #region Create appliance

            XenRef<VM_appliance> applRef = null;
            if (ApplianceName != null)
            {
                var vmAppliance = new VM_appliance {name_label = ApplianceName, Connection = xenSession.Connection};
                applRef = VM_appliance.create(xenSession, vmAppliance);
            }

            #endregion

            foreach (VirtualSystem_Type vSystem in ((VirtualSystemCollection_Type)ovfObj.Item).Content)
            {
               //FIND/SET THE NAME OF THE VM
                ovfname = OVF.FindSystemName(ovfObj, vSystem.id);
                auditLog.DebugFormat("Import: {0}, {1}", ovfname, pathToOvf);

                VirtualHardwareSection_Type vhs = OVF.FindVirtualHardwareSectionByAffinity(ovfObj, vSystem.id, "xen");

                XenRef<VM> vmRef = DefineSystem(xenSession, vhs, ovfname);
                if (vmRef == null)
                {
                    log.Error(Messages.ERROR_CREATE_VM_FAILED);
                    throw new ImportException(Messages.ERROR_CREATE_VM_FAILED);
                }

                HideSystem(xenSession, vmRef);
                log.DebugFormat("OVF.Import.Process: DefineSystem completed ({0})", VM.get_name_label(xenSession, vmRef));

                #region Set appliance
                if (applRef != null)
                    VM.set_appliance(xenSession, vmRef.opaque_ref, applRef.opaque_ref);

                if (ovfObj.Sections != null)
                {
                    StartupSection_Type[] startUpArray = OVF.FindSections<StartupSection_Type>(ovfObj.Sections);
                    if (startUpArray != null && startUpArray.Length > 0)
                    {
                        var startupSection = startUpArray[0];
                        var itemList = startupSection.Item;

                        if (itemList != null)
                        {
                            var item = itemList.FirstOrDefault(it => it.id == vSystem.id);

                            if (item != null)
                            {
                                VM.set_start_delay(xenSession, vmRef.opaque_ref, item.startDelay);
                                VM.set_shutdown_delay(xenSession, vmRef.opaque_ref, item.stopDelay);
                                VM.set_order(xenSession, vmRef.opaque_ref, item.order);
                            }
                        }
                    }
                }

                #endregion

                #region set has_vendor_device

                if (Helpers.DundeeOrGreater(xenSession.Connection))
                {
                    var data = vhs.VirtualSystemOtherConfigurationData;
                    if (data != null)
                    {
                        var datum = data.FirstOrDefault(s => s.Name == "VM_has_vendor_device");
                        if (datum != null)
                        {
                            bool hasVendorDevice;
                            if (bool.TryParse(datum.Value.Value, out hasVendorDevice) && hasVendorDevice)
                                VM.set_has_vendor_device(xenSession, vmRef.opaque_ref, hasVendorDevice);
                        }
                    }
                }

                #endregion

                #region Set vgpu

                GPU_group gpuGroup;
                VGPU_type vgpuType;
                FindGpuGroupAndVgpuType(xenSession, vhs, out gpuGroup, out vgpuType);

                if (gpuGroup != null)
                {
                    var other_config = new Dictionary<string, string>();

                    if (Helpers.FeatureForbidden(xenSession, Host.RestrictVgpu))
                        VGPU.create(xenSession, vmRef.opaque_ref, gpuGroup.opaque_ref, "0", other_config);
                    else if (vgpuType != null)
                        VGPU.create(xenSession, vmRef.opaque_ref, gpuGroup.opaque_ref, "0", other_config, vgpuType.opaque_ref);
                }

                #endregion

                SetDeviceConnections(ovfObj, vhs);
                try
                {
                    foreach (RASD_Type rasd in vhs.Item)
                    {
                        string thisPassCode = null;
                        // Check to see if THIS rasd is encrypted, if so, set the passcode.
                        if (OVF.IsThisEncrypted(ovfObj, rasd))
                            thisPassCode = passcode;

                        string compression = "None";
                        if (rasd.ResourceType.Value == 17 || rasd.ResourceType.Value == 19 || rasd.ResourceType.Value == 21)
                        {
                            bool skip = Tools.ValidateProperty("Caption", rasd) &&
                                 (
                                  rasd.Caption.Value.ToUpper().Contains("COM") ||
                                  rasd.Caption.Value.ToUpper().Contains("FLOPPY") ||
                                  rasd.Caption.Value.ToUpper().Contains("ISO")
                                 );

                            if (!skip)
                            {
                                File_Type file = OVF.FindFileReferenceByRASD(ovfObj, rasd);
                                if (file == null)
                                    continue;

                                if (IsKnownURIType(file.href))
                                    _filedownloadsize = file.size;

                                VirtualDiskDesc_Type vdisk = OVF.FindDiskReference(ovfObj, rasd);
                                SetIfDeviceIsBootable(ovfObj, rasd);
                                AdditionalSpace = OVF.ComputeCapacity(Convert.ToInt64(vdisk.capacity), vdisk.capacityAllocationUnits);  // used in Wim file imports only.
                                AddResourceSettingData(xenSession, vmRef, rasd, pathToOvf, OVF.FindRasdFileName(ovfObj, rasd, out compression), compression, encryptionVersion, thisPassCode);
                            }
                        }
                        else
                        {
                            AddResourceSettingData(xenSession, vmRef, rasd, pathToOvf, OVF.FindRasdFileName(ovfObj, rasd, out compression), compression, encryptionVersion, thisPassCode);
                        }
                    }

                    InstallSection_Type[] installSection = OVF.FindSections<InstallSection_Type>(vSystem.Items);

                    if (installSection != null && installSection.Length == 1)
                    {
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOn, "Import", Messages.START_POST_INSTALL_INSTRUCTIONS));
                        OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ImportProgress, "Import", Messages.START_POST_INSTALL_INSTRUCTIONS));
                        HandleInstallSection(xenSession, vmRef, installSection[0]);
                    }
                    ShowSystem(xenSession, vmRef);
                }
                catch (Exception ex)
                {
                    if (ex is OperationCanceledException)
                        throw;
                    log.Error(Messages.ERROR_IMPORT_FAILED);
                    throw new Exception(Messages.ERROR_IMPORT_FAILED, ex);
                }
            }

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.MarqueeOff, "Import", ""));
            int _processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            string _touchFile = Path.Combine(pathToOvf, "xen__" + _processId);
            //added check again as Delete needs write permissions and even if the file does not exist import will fail if the user has read only permissions
            if (File.Exists(_touchFile))
                File.Delete(_touchFile);

            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ImportThreadComplete, "Import", Messages.COMPLETED_IMPORT));
        }
예제 #16
0
        protected override void Run()
        {
            log.Debug("Running SR Reconfigure Action");
            log.DebugFormat("SR uuid = '{0}'", sr.uuid);
            log.DebugFormat("name = '{0}'", name);
            log.DebugFormat("description = '{0}'", description);

            Description = Messages.ACTION_SR_ATTACHING;

            // Repair the SR with new PBDs for each host in the pool
            PBD pbdTemplate = new PBD();
            pbdTemplate.currently_attached = false;
            pbdTemplate.device_config = dconf;
            pbdTemplate.SR = new XenRef<SR>(sr.opaque_ref);

            int delta = 100 / (Connection.Cache.HostCount * 2);
            foreach (Host host in Connection.Cache.Hosts)
            {
                // Create the PBD
                log.DebugFormat("Creating PBD for host {0}", host.Name);
                this.Description = String.Format(Messages.ACTION_SR_REPAIR_CREATE_PBD, Helpers.GetName(host));
                pbdTemplate.host = new XenRef<Host>(host.opaque_ref);
                RelatedTask = PBD.async_create(this.Session, pbdTemplate);
                PollToCompletion(PercentComplete, PercentComplete + delta);
                XenRef<PBD> pbdRef = new XenRef<PBD>(this.Result);

                // Now plug the PBD
                log.DebugFormat("Plugging PBD for host {0}", host.Name);
                this.Description = String.Format(Messages.ACTION_SR_REPAIR_PLUGGING_PBD, Helpers.GetName(host));
                RelatedTask = PBD.async_plug(this.Session, pbdRef);
                PollToCompletion(PercentComplete, PercentComplete + delta);
            }

            // Update the name and description of the SR
            XenAPI.SR.set_name_label(Session, sr.opaque_ref, name);
            XenAPI.SR.set_name_description(Session, sr.opaque_ref, description);

            Description = Messages.ACTION_SR_ATTACH_SUCCESSFUL;
        }
예제 #17
0
        private void ConfigureForXenServer(Session xenSession, XenRef<VM> vm)
        {
            // Ensure the new VM is down.
            if (VM.get_power_state(xenSession, vm) != vm_power_state.Halted)
                VM.hard_shutdown(xenSession, vm);

            while (VM.get_power_state(xenSession, vm) != vm_power_state.Halted)
                Thread.Sleep(Properties.Settings.Default.FixupPollTimeAsMs);

            // Save its original memory configuration.
            long staticMemoryMin  = VM.get_memory_static_min(xenSession, vm);
            long staticMemoryMax  = VM.get_memory_static_max(xenSession, vm);
            long dynamicMemoryMin = VM.get_memory_dynamic_min(xenSession, vm);
            long dynamicMemoryMax = VM.get_memory_dynamic_max(xenSession, vm);

            // Minimize the memory capacity for the fixup OS.
            long fixupMemorySize = Properties.Settings.Default.FixupOsMemorySizeAsMB * MB;

            VM.set_memory_limits(xenSession, vm, fixupMemorySize, fixupMemorySize, fixupMemorySize, fixupMemorySize);

            // Run the fixup OS on the VM.
            InstallSectionStartVirtualMachine(xenSession, vm, Properties.Settings.Default.FixupDurationAsSeconds);

            // Restore the original memory configuration.
            VM.set_memory_limits(xenSession, vm, staticMemoryMin, staticMemoryMax, dynamicMemoryMin, dynamicMemoryMax);

            // Eject the fixupOS CD.
            List<XenRef<VBD>> vbdList = VM.get_VBDs(xenSession, vm);
            foreach (XenRef<VBD> vbd in vbdList)
            {
                if (VBD.get_type(xenSession, vbd) == vbd_type.CD)
                    VBD.eject(xenSession, vbd);

                // Note that the original code did not destroy the VBD representing the CD drive.
            }

            // Restore the boot order.
            Dictionary<string, string> bootParameters = new Dictionary<string, string>();
            bootParameters.Add("order", "cnd");
            VM.set_HVM_boot_params(xenSession, vm, bootParameters);
        }
예제 #18
0
        /// <summary>
        /// Get the persisted secret from the server, or prompt for new credentials and persist those back to the server.
        /// Completion of this thread is indicated by state.Credentials being set.
        /// </summary>
        /// <param name="obj"></param>
        private void GetSecret(object obj)
        {
            Program.AssertOffEventThread();

            BrowserState state = (BrowserState)obj;

            try
            {
                Session session = state.Obj.Connection.Session;

                do
                {
                    Pool pool = Helpers.GetPoolOfOne(state.Obj.Connection);
                    if (pool == null)
                    {
                        log.Warn("Failed to get Pool!");
                        Thread.Sleep(5000);
                        continue;
                    }

                    string secret_uuid = pool.GetXCPluginSecret(PluginDescriptor.Name, state.Obj);
                    if (string.IsNullOrEmpty(secret_uuid))
                    {
                        var msg = secret_uuid == null ? "Nothing persisted." : "User chose not to persist these credentials.";
                        log.Debug(msg + " Prompting for new credentials.");

                        Program.Invoke(Program.MainWindow, () => { state.Credentials = PromptForUsernamePassword(secret_uuid == null); });
                        MaybePersistCredentials(session, pool, state.Obj, state.Credentials);
                        return;
                    }
                    else
                    {
                        log.Debug("Found a secret.");
                        XenRef <Secret> secret = null;
                        try
                        {
                            secret = Secret.get_by_uuid(session, secret_uuid);
                        }
                        catch (Failure exn)
                        {
                            log.Warn(string.Format("Secret with uuid {0} for {1} on plugin {2} has disappeared! Removing from pool.gui_config.",
                                                   secret_uuid, Helpers.GetName(state.Obj), PluginDescriptor.Name), exn);
                            TryToRemoveSecret(pool, session, PluginDescriptor.Name, state.Obj);
                            continue;
                        }

                        string   val  = Secret.get_value(session, secret);
                        string[] bits = val.Split(CREDENTIALS_SEPARATOR);
                        if (bits.Length != 2)
                        {
                            log.WarnFormat("Corrupt secret with uuid {0} for {1} on plugin {2}! Deleting.", secret_uuid,
                                           Helpers.GetName(state.Obj), PluginDescriptor.Name);

                            TryToDestroySecret(session, secret.opaque_ref);
                            TryToRemoveSecret(pool, session, PluginDescriptor.Name, state.Obj);
                            continue;
                        }

                        log.Debug("Secret successfully read.");

                        state.Credentials = new BrowserState.BrowserCredentials
                        {
                            Username           = bits[0],
                            Password           = bits[1],
                            PersistCredentials = true,
                            Valid = true
                        };
                        return;
                    }

                    // Unreachable.  Should either have returned, or continued (to retry).
                } while (true);
            }
            catch (Exception exn)
            {
                log.Warn("Ignoring exception when trying to get secret", exn);

                // Note that it's essential that we set state.Credentials before leaving this function,
                // because other threads are waiting for that value to appear.
                state.Credentials = new BrowserState.BrowserCredentials {
                    Valid = false
                };
            }
        }
예제 #19
0
        private static String PollTaskForResult(IXenConnection connection, ref Session session,
            HTTP.FuncBool cancellingDelegate, XenRef<Task> task, bool timeout = false)
        {
            //Program.AssertOffEventThread();

            task_status_type status;
            int tries = POLL_FOR_TASK_RESULT_TIMEOUT / POLL_FOR_TASK_RESULT_SLEEP_INTERVAL;
            do
            {
                if (cancellingDelegate != null && cancellingDelegate())
                    throw new XenAdmin.CancelledException();

                System.Threading.Thread.Sleep(POLL_FOR_TASK_RESULT_SLEEP_INTERVAL);
                tries--;

                status = (task_status_type)Task.DoWithSessionRetry(connection, ref session,
                    (Task.TaskStatusOp)Task.get_status, task.opaque_ref);
            }
            while ((status == task_status_type.pending || status == task_status_type.cancelling) && (!timeout || tries > 0));

            if (cancellingDelegate != null && cancellingDelegate())
                throw new XenAdmin.CancelledException();

            if (status == task_status_type.failure)
            {
                throw new Failure(Task.get_error_info(session, task));
            }
            else
            {
                return Task.get_result(session, task);
            }
        }
예제 #20
0
        private void generatePoolHABox(Pool pool)
        {
            if (!pool.ha_enabled)
            {
                return;
            }

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

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

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

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

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

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

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

            // Now build the heartbeat target health table

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

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

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

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

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

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

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

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

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

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

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

            tableLatencies.ResumeLayout();
            tableLatencies.PerformLayout();
        }
예제 #21
0
        private string UploadSupplementalPack(SR sr)
        {
            this.Description = String.Format(Messages.SUPP_PACK_UPLOADING_TO, sr.Name);

            String result;

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

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

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

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

            Host localStorageHost = sr.GetStorageHost();

            string hostUrl;

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

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

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

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

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

                if (vdiRef != null)
                {
                    log.DebugFormat("Removing the VDI on a best effort basis.");

                    try
                    {
                        RemoveVDI(Session, vdiRef);
                    }
                    catch (Exception removeEx)
                    {
                        //best effort
                        log.Error("Failed to remove the VDI.", removeEx);
                    }
                }

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

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

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

                    if (poolUpdate == null)
                    {
                        throw new Exception(Messages.UPDATE_ERROR_INTRODUCE); // This should not happen, because such case will result in a XAPI Failure. But this code has to be protected at this point.
                    }
                    VdiRefsToCleanUp.Clear();
                }
                catch (Failure ex)
                {
                    if (ex.ErrorDescription != null && ex.ErrorDescription.Count > 1 && string.Equals("UPDATE_ALREADY_EXISTS", ex.ErrorDescription[0], StringComparison.InvariantCultureIgnoreCase))
                    {
                        string uuidFound = ex.ErrorDescription[1];

                        poolUpdate = Connection.Cache.Pool_updates.FirstOrDefault(pu => string.Equals(pu.uuid, uuidFound, System.StringComparison.InvariantCultureIgnoreCase));

                        //clean-up the VDI we've just created
                        try
                        {
                            RemoveVDI(Session, vdiRef);

                            //remove the vdi that have just been cleaned up
                            var remaining = VdiRefsToCleanUp.Where(kvp => kvp.Value != null && kvp.Value.opaque_ref != vdiRef.opaque_ref).ToList();
                            VdiRefsToCleanUp.Clear();
                            remaining.ForEach(rem => VdiRefsToCleanUp.Add(rem.Key, rem.Value));
                        }
                        catch
                        {
                            //best effort cleanup
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Upload failed when introducing update from VDI {0} on {1}: {2}", vdi.opaque_ref, Connection, ex.Message);
                    poolUpdate = null;

                    throw;
                }
            }
            else
            {
                poolUpdate = null;
            }

            totalUploaded++;
            Description = String.Format(Messages.SUPP_PACK_UPLOADED, sr.Name);
            return(result);
        }
예제 #22
0
파일: Cache.cs 프로젝트: wranders/xenadmin
 public void AddFolder(XenRef <Folder> path, Folder folder)
 {
     _folders[path] = folder;
     foldersChanged = true;
 }
예제 #23
0
파일: Cache.cs 프로젝트: wranders/xenadmin
 public bool TryResolve <T>(XenRef <T> xenRef, out T result) where T : XenObject <T>
 {
     result = Resolve(xenRef);
     return(result != null);
 }
예제 #24
0
        protected override void Run()
        {
            Description = String.Format(Messages.ACTION_VDI_LOAD_METADATA_STATUS, Connection.Resolve(_poolMetadata.Vdi.SR).Name());
            log.DebugFormat("Loading metadata from VDI '{0}' on SR '{1}'", _poolMetadata.Vdi.Name(),
                            Connection.Resolve(_poolMetadata.Vdi.SR).Name());

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

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

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

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

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

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

                    PercentComplete = 50;

                    Dictionary <XenRef <VM>, VM> vms = VM.get_all_records(MetadataSession);
                    foreach (var vmRef in vms.Keys)
                    {
                        VM vm = vms[vmRef];
                        if (!vm.is_a_real_vm())
                        {
                            continue;
                        }
                        vm.opaque_ref = vmRef.opaque_ref;
                        _poolMetadata.Vms.Add(vmRef, vm);
                    }
                }
                catch (Exception)
                {
                }
            }
            PercentComplete = 100;
            Description     = Messages.ACTION_VDI_LOAD_METADATA_DONE;
        }
예제 #25
0
 /// <summary>
 /// Try to forget an SR that has previously failed to completely plug.  Nothrow guarantee.
 /// </summary>
 private void ForgetFailedSR(XenRef<SR> sr)
 {
     try
     {
         foreach (XenRef<PBD> pbd in XenAPI.SR.get_PBDs(Session, sr.opaque_ref))
         {
             if (PBD.get_currently_attached(Session, pbd))
                 PBD.unplug(Session, pbd);
         }
         XenAPI.SR.forget(Session, sr.opaque_ref);
     }
     catch
     {
         log.Debug("SR.forget() failed! Continuing anyway");
     }
 }
예제 #26
0
 private void HideSystem(Session xenSession, XenRef<VM> vmRef)
 {
     VM.add_to_other_config(xenSession, vmRef, "HideFromXenCenter", "true");
 }
예제 #27
0
 private void RemoveSystem(Session xenSession, XenRef<VM> vm)
 {
     try
     {
         VM.destroy(xenSession, vm);
     }
     catch (Exception ex)
     {
         log.ErrorFormat("{0} {1}", Messages.ERROR_REMOVE_VM_FAILED, ex.Message);
         throw new Exception(Messages.ERROR_REMOVE_VM_FAILED, ex);
     }
     return;
 }
예제 #28
0
 private void ShowSystem(Session xenSession, XenRef<VM> vmRef)
 {
     VM.remove_from_other_config(xenSession, vmRef, "HideFromXenCenter");
 }
예제 #29
0
        private void HandleInstallSection(Session xenSession, XenRef<VM> vm, InstallSection_Type installsection)
        {
            // Configure for XenServer as requested by OVF.SetRunOnceBootCDROM() with the presence of a post install operation that is specific to XenServer.
            if (installsection.PostInstallOperations != null)
                ConfigureForXenServer(xenSession, vm);

            // Run the VM for the requested duration if this appliance had its own install section -- one not added to fixup for XenServer.
            if (((installsection.Info == null)) ||
                ((installsection.Info != null) && (installsection.Info.Value.CompareTo("ConfigureForXenServer") != 0)))
                InstallSectionStartVirtualMachine(xenSession, vm, installsection.initialBootStopDelay);
        }
예제 #30
0
 private SR RetrieveSR(XenRef <SR> xenRefSr)
 {
     return(SR.get_record(MetadataSession, xenRefSr));
 }
예제 #31
0
        private void InstallSectionStartVirtualMachine(Session xenSession, XenRef<VM> vm, int initialBootStopDelayAsSeconds)
        {
            // Start the VM.
            if (VM.get_power_state(xenSession, vm) != vm_power_state.Running)
                VM.start(xenSession, vm, false, true);

            // Finish early if requested to stop on its own.
            if (initialBootStopDelayAsSeconds == 0)
                return;

            // Wait for it to start.
            while (VM.get_power_state(xenSession, vm) != vm_power_state.Running)
                Thread.Sleep(Properties.Settings.Default.FixupPollTimeAsMs);

            // Let it run for the requested duration.
            int bootStopDelayAsMs = initialBootStopDelayAsSeconds * 1000;
            int msRunning = 0;

            while (VM.get_power_state(xenSession, vm) == vm_power_state.Running)
            {
                Thread.Sleep(Properties.Settings.Default.FixupPollTimeAsMs);
                msRunning += Properties.Settings.Default.FixupPollTimeAsMs;

                if (msRunning > bootStopDelayAsMs)
                    break;
            }

            // Ensure it is off.
            if (VM.get_power_state(xenSession, vm) != vm_power_state.Halted)
                VM.hard_shutdown(xenSession, vm);
        }
예제 #32
0
        private static String PollTaskForResult(IXenConnection connection, ref Session session,
            HTTP.FuncBool cancellingDelegate, XenRef<Task> task)
        {
            //Program.AssertOffEventThread();

            task_status_type status;

            do
            {
                if (cancellingDelegate != null && cancellingDelegate())
                    throw new XenAdmin.CancelledException();

                System.Threading.Thread.Sleep(500);

                status = (task_status_type)Task.DoWithSessionRetry(connection, ref session,
                    (Task.TaskStatusOp)Task.get_status, task.opaque_ref);
            }
            while (status == task_status_type.pending || status == task_status_type.cancelling);

            if (cancellingDelegate != null && cancellingDelegate())
                throw new XenAdmin.CancelledException();

            if (status == task_status_type.failure)
            {
                throw new Failure(Task.get_error_info(session, task));
            }
            else
            {
                return Task.get_result(session, task);
            }
        }
예제 #33
0
 private void RemoveVDI(Session xenSession, XenRef<VDI> vdi)
 {
     try
     {
         log.Error("OVF.Import.RemoveVDI: Something went wrong deleting associated VDI");
         VDI.destroy(xenSession, vdi.opaque_ref);
     }
     catch (Exception ex)
     {
         log.ErrorFormat("{0}, {1}", Messages.ERROR_REMOVE_VDI_FAILED, ex.Message);
         throw new Exception(Messages.ERROR_REMOVE_VDI_FAILED, ex);
     }
     return;
 }
예제 #34
0
        private void SetupMocks(List<XenServerPatch> xenServerPatches, List<XenServerVersion> xenServerVersions)
        {
            Mock<Host>  master = mom.NewXenObject<Host>(id);
            Mock<Pool> pool = mom.NewXenObject<Pool>(id);
            XenRef<Host> masterRef = new XenRef<Host>("ref");
            pool.Setup(p => p.master).Returns(masterRef);
            mom.MockCacheFor(id).Setup(c => c.Resolve(It.IsAny<XenRef<Pool>>())).Returns(pool.Object);
            mom.MockConnectionFor(id).Setup(c => c.Resolve(masterRef)).Returns(master.Object);
            master.Setup(h => h.software_version).Returns(new Dictionary<string, string>());
            master.Setup(h => h.ProductVersion).Returns(ServerVersion);
            master.Setup(h => h.AppliedPatches()).Returns(GenerateMockPoolPatches(xenServerPatches));

            //Currently build number will be referenced first so if it's present hook it up
            string buildNumber = xenServerVersions.First(v => v.Version.ToString() == ServerVersion).BuildNumber;
            master.Setup(h=>h.BuildNumberRaw).Returns(buildNumber);
        }
예제 #35
0
        private XenRef<VDI> UploadiSCSI(Session xenSession, string sruuid, string label, Stream filestream, long capacity, string description, string vdiuuid)
        {
            log.Debug("OVF.Import.UploadiSCSI Enter");
            log.DebugFormat("OVF.Import.UploadiSCSI SRUUID: {0}", sruuid);
            log.DebugFormat("OVF.Import.UploadiSCSI Label: {0}", label);
            log.DebugFormat("OVF.Import.UploadiSCSI Capacity: {0}", capacity);

            XenRef<VDI> vdiRef = null;

            //If no VDI uuid is provided create a VDI, otherwise use the one provided as
            //the target for the import. Used for SRs such as Lun per VDI (PR-1544)
            if(String.IsNullOrEmpty(vdiuuid))
            {
                vdiRef = CreateVDI(xenSession, sruuid, label, capacity, description);
                vdiuuid = VDI.get_uuid(xenSession, vdiRef);
            }
            else
            {
                vdiRef = new XenRef<VDI>(VDI.get_by_uuid(xenSession, vdiuuid));
            }

            #region UPLOAD iSCSI STREAM
            OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.FileStart, "Import", string.Format(Messages.FILES_TRANSPORT_SETUP, _currentfilename)));
            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
            {
                using (Stream iSCSIStream = m_iscsi.Connect(xenSession, vdiuuid, false))
                {
                    m_iscsi.Copy(filestream, iSCSIStream, label, false);
                    iSCSIStream.Flush();
                }
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                    throw;
                log.ErrorFormat("{0} {1}", Messages.ERROR_ISCSI_UPLOAD_FAILED, ex.Message);
                vdiRef = null;
                throw new Exception(Messages.ERROR_ISCSI_UPLOAD_FAILED, ex);
            }
            finally
            {
                OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.FileStart, "Import", string.Format(Messages.FILES_TRANSPORT_CLEANUP,_currentfilename)));
                m_iscsi.Disconnect(xenSession);
            }
            #endregion

            log.Debug("OVF.Import.UploadiSCSI Leave");
            return vdiRef;
        }
예제 #36
0
        private void LoadPoolMetadata(VDI vdi)
        {
            Session metadataSession = null;
            try
            {
                VdiLoadMetadataAction action = new VdiLoadMetadataAction(Connection, vdi);
                ActionProgressDialog dialog = new ActionProgressDialog(action, ProgressBarStyle.Marquee);
                dialog.ShowDialog(this); //Will block until dialog closes, action completed

                if (action.Succeeded && action.MetadataSession != null)
                {
                    metadataSession = action.MetadataSession;
                    XenRef<VDI> vdiRef = new XenRef<VDI>(vdi);
                    if (action.PoolMetadata != null && !allPoolMetadata.ContainsKey(vdiRef))
                    {
                        allPoolMetadata.Add(vdiRef, action.PoolMetadata);
                    }
                }

            }
            finally
            {
                if (metadataSession != null)
                    metadataSession.logout();
            }
        }
예제 #37
0
        private string VerifyUserDevice(Session xenSession, XenRef<VM> vmRef, string device)
        {
            log.DebugFormat("Import.VerifyUserDevice, checking device: {0} (99 = autoselect)", device);
            string usethisdevice = null;
            List<XenRef<VBD>> vbds = VM.get_VBDs(xenSession, vmRef);
            string[] allowedVBDs = VM.get_allowed_VBD_devices(xenSession, vmRef);

            if (allowedVBDs == null || allowedVBDs.Length <= 0)
            {
                string message = string.Format("OVF.VerifyUserDevice: No more available devices, cannot add device: {0}", device);
                log.Error(message);
                return device + "+";
            }

            if (!string.IsNullOrEmpty(device) && !device.StartsWith("99"))
            {
                foreach (string allowedvbd in allowedVBDs)
                {
                    if (device.ToLower() == allowedvbd.ToLower())
                    {
                        usethisdevice = device;
                        log.DebugFormat("Import.VerifyUserDevice, device: {0} will be used.", device);
                        break;
                    }
                }
            }
            else
            {
                usethisdevice = allowedVBDs[0];
                log.DebugFormat("Import.VerifyUserDevice, device [{0}] is not available, setting to: [{1}]", device, usethisdevice);
            }

            if (usethisdevice == null)
            {
                if (!device.EndsWith("+"))
                    usethisdevice = device + "+";
            }
            return usethisdevice;
        }
예제 #38
0
 protected void PerformSilentTaskOp(Action f)
 {
     if (_relatedTask == null)
         return;
     try
     {
         f();
     }
     catch (XenAPI.Failure exn)
     {
         if (exn.ErrorDescription.Count > 1 &&
             exn.ErrorDescription[0] == XenAPI.Failure.HANDLE_INVALID &&
             exn.ErrorDescription[1] == "task")
         {
             log.Debug(exn, exn);
             // The task has disappeared.
             _relatedTask = null;
         }
         else
         {
             log.Error(exn, exn);
             // Ignore, and hope that this isn't a problem.
         }
     }
     catch (Exception exn)
     {
         log.Error(exn, exn);
         // Ignore, and hope that this isn't a problem.
     }
 }
예제 #39
0
 protected RebootPlanAction(IXenConnection connection, XenRef<Host> host, String title)
     : base(connection, title)
 {
     this.Host = host;
 }
예제 #40
0
        protected override void Run()
        {
            log.DebugFormat("Running SrActionKind.{0}", kind.ToString());

            int inc = SR.PBDs.Count > 0 ? 100 / (SR.PBDs.Count * 2) : 0;

            switch (kind)
            {
            case SrActionKind.Detach:
                UnplugPBDs(ref inc);
                Description = string.Format(Messages.ACTION_SR_DETACH_SUCCESSFUL, SR.NameWithoutHost);
                break;

            case SrActionKind.Destroy:
                if (!Helpers.TampaOrGreater(Connection))
                {
                    UnplugPBDs(ref inc);
                }
                RelatedTask = XenAPI.SR.async_destroy(Session, SR.opaque_ref);
                PollToCompletion(50, 100);
                Description = Messages.ACTION_SR_DESTROY_SUCCESSFUL;
                break;

            case SrActionKind.Forget:
                Description = string.Format(Messages.FORGETTING_SR_0, SR.NameWithoutHost);
                if (!Helpers.TampaOrGreater(Connection) && !SR.IsDetached && SR.IsDetachable())
                {
                    UnplugPBDs(ref inc);
                }
                if (!SR.allowed_operations.Contains(storage_operations.forget))
                {
                    Description = Messages.ERROR_DIALOG_FORGET_SR_TITLE;
                    break;
                }

                RelatedTask = XenAPI.SR.async_forget(Session, SR.opaque_ref);
                PollToCompletion();
                Description = string.Format(Messages.SR_FORGOTTEN_0, SR.NameWithoutHost);
                break;

            case SrActionKind.SetAsDefault:
                XenRef <SR> r = new XenRef <SR>(SR);
                Pool        = Helpers.GetPoolOfOne(Connection);
                Description = string.Format(Messages.ACTION_SR_SETTING_DEFAULT, SR, Pool);
                Pool poolCopy = (Pool)Pool.Clone();
                if (Pool != null)
                {
                    poolCopy.crash_dump_SR    = r;
                    poolCopy.default_SR       = r;
                    poolCopy.suspend_image_SR = r;
                    try
                    {
                        Pool.Locked = true;
                        poolCopy.SaveChanges(Session);
                    }
                    finally
                    {
                        Pool.Locked = false;
                    }
                }

                Description = Messages.ACTION_SR_SET_DEFAULT_SUCCESSFUL;
                break;

            case SrActionKind.UpgradeLVM:
                Description = Messages.ACTION_SR_CONVERTING;

                XenAPI.SR.remove_from_sm_config(Session, SR.opaque_ref, XenAPI.SR.USE_VHD);
                XenAPI.SR.add_to_sm_config(Session, SR.opaque_ref, XenAPI.SR.USE_VHD, "true");

                Description = Messages.ACTION_SR_CONVERTED;
                break;

            case SrActionKind.UnplugAndDestroyPBDs:
                UnplugPBDs(ref inc);
                DestroyPBDs(ref inc);
                Description = string.Format(Messages.ACTION_SR_DETACH_SUCCESSFUL, SR.NameWithoutHost);
                break;

            case SrActionKind.ConvertToThin:
                Description = string.Format(Messages.ACTION_SR_CONVERTING_TO_THIN, SR.NameWithLocation);

                long initial_allocation = 0;
                long allocation_quantum = 0;

                if (parameters != null)
                {
                    if (parameters.ContainsKey("initial_allocation"))
                    {
                        long.TryParse(parameters["initial_allocation"], out initial_allocation);
                    }

                    if (parameters.ContainsKey("allocation_quantum"))
                    {
                        long.TryParse(parameters["allocation_quantum"], out allocation_quantum);
                    }
                }

                LVHD.enable_thin_provisioning(Session, SR.uuid, initial_allocation, allocation_quantum);

                Description = string.Format(Messages.ACTION_SR_CONVERTED_TO_THIN, SR.NameWithLocation);
                break;
            }
        }