void setProjectConnectorRelationship(ref CreatableEnterpriseManagementObject project)
        {
            CreatableEnterpriseManagementRelationshipObject cemroConnector =
                new CreatableEnterpriseManagementRelationshipObject(emg, mprRelationships.First(r => r.Name == "System.ProjectConfigItemRelatesToProjectConnector"));

            cemroConnector.SetSource(emoConnector);
            cemroConnector.SetTarget(project);
            iddObjects.Add(cemroConnector);
        }
 private void NewTestDialog_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (e.CloseReason == CloseReason.None && DialogResult == DialogResult.OK)
     {
         try
         {
             IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData();
             incrementalDiscovery.Add(CreatableObjectAdapter.BaseObject);
             EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
             if (ExistingObject == null)
             {
                 incrementalDiscovery.Commit(connector); // new
             }
             else
             {
                 incrementalDiscovery.Overwrite(connector); // update
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show($"Failed to create new test object.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
             e.Cancel = true;
             return;
         }
     }
 }
 /// <summary>
 /// Updates the specified model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="isPolling">if set to <c>true</c> [is polling].</param>
 /// <exception cref="System.Exception"></exception>
 public void Update(Enclosure model, bool isPolling)
 {
     try
     {
         HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Start UpdateEnclosure.[{model.UnionId}] [isPolling:{isPolling}]");
         var exsitEnclosure = this.GetObject($"UnionId = '{model.UnionId}'", this.EnclosureClass);
         if (exsitEnclosure == null)
         {
             throw new Exception($"Can not find the server:{model.UnionId}");
         }
         var isChange = CompareEnclosure(model, exsitEnclosure);
         if (isChange)
         {
             var discoveryData = new IncrementalDiscoveryData();
             this.UpdateEnclosure(model, exsitEnclosure);
             discoveryData.Add(exsitEnclosure);
             discoveryData.Overwrite(this.MontioringConnector);
             HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Info($"Update enclosure finish.[{model.UnionId}]");
         }
     }
     catch (Exception e)
     {
         HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Update enclosure error.[{model.UnionId}] [isPolling:{isPolling}]");
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Updates the specified appliance.
        /// </summary>
        /// <param name="appliance">The appliance.</param>
        /// <param name="isUpdateCredential">是否修改了密码</param>
        /// <returns>Result.</returns>
        public async Task <Result> Update(FdAppliance appliance, bool isUpdateCredential)
        {
            return(await Task.Run(async() =>
            {
                try
                {
                    var obj = await this.FindByHost(appliance.HostIP);
                    var exsitObj = obj.Data;
                    if (exsitObj == null)
                    {
                        return Result.Failed(104, $"Fd {appliance.HostIP} can not find.");
                    }
                    var incrementalDiscoveryData = new IncrementalDiscoveryData();

                    var props = this.FdApplianceClass.PropertyCollection;
                    exsitObj[props["AliasName"]].Value = appliance.AliasName;
                    exsitObj[props["Port"]].Value = appliance.Port;
                    exsitObj[props["LastModifyTime"]].Value = appliance.LastModifyTime;

                    if (isUpdateCredential)
                    {
                        try
                        {
                            var eventAccount = exsitObj[props["EventUserName"]].Value as string;
                            var eventPd = exsitObj[props["EventPd"]].Value as string;
                            if (eventAccount != appliance.EventUserName || eventPd != appliance.EventPd)
                            {
                                using (var client = new FdClient(appliance))
                                {
                                    var res = await client.DeleteGivenSubscriptions(appliance.SubscribeId);
                                    LogHelper.Info($"Update Fd:DeleteGivenSubscriptions:{res.Code} {res.Message}");
                                    // 取消订阅后重置订阅状态
                                    exsitObj[props["SubscribeId"]].Value = string.Empty;
                                    exsitObj[props["SubscribeStatus"]].Value = string.Empty;
                                    exsitObj[props["LatestSubscribeInfo"]].Value = string.Empty;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error("DeleteSubscriptions Faild", ex);
                        }
                        exsitObj[props["LoginAccount"]].Value = appliance.LoginAccount;
                        exsitObj[props["LoginPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.LoginPd);
                        exsitObj[props["EventUserName"]].Value = appliance.EventUserName;
                        exsitObj[props["EventPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.EventPd);
                    }

                    incrementalDiscoveryData.Add(exsitObj);
                    incrementalDiscoveryData.Overwrite(MGroup.Instance);

                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
        public async Task <Result> Add(ESightAppliance appliance)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    if (OM12Connection.Exsits(ESightAppliance.EntityClassName, $"Host='{appliance.Host}'"))
                    {
                        return Result.Failed(101, $"ESight {appliance.Host} already exsits.");
                    }

                    IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData();

                    // add appliance record
                    ManagementPackClass MPClass = GetMPClass();
                    CreatableEnterpriseManagementObject EMOAppliance =
                        new CreatableEnterpriseManagementObject(OM12Connection.HuaweiESightMG, MPClass);
                    IDictionary <string, ManagementPackProperty> props =
                        OM12Connection.GetManagementPackProperties(EMOAppliance);
                    EMOAppliance[props["Host"]].Value = appliance.Host;
                    EMOAppliance[props["Port"]].Value = appliance.Port;
                    EMOAppliance[props["AliasName"]].Value = appliance.AliasName;
                    EMOAppliance[props["SystemId"]].Value = appliance.SystemId;
                    EMOAppliance[props["LoginAccount"]].Value = appliance.LoginAccount;
                    EMOAppliance[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance
                                                                 .EncryptForCS(appliance.LoginPassword);
                    EMOAppliance[props["LastModifiedOn"]].Value = DateTime.UtcNow;
                    EMOAppliance[props["CreatedOn"]].Value = DateTime.UtcNow;

                    EMOAppliance[props["OpenID"]].Value = Guid.NewGuid().ToString("D");
                    EMOAppliance[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D");
                    EMOAppliance[props["SubKeepAliveStatus"]].Value = 0;
                    EMOAppliance[props["SubscriptionAlarmStatus"]].Value = 0;
                    EMOAppliance[props["SubscriptionNeDeviceStatus"]].Value = 0;

                    EMOAppliance[props["SubKeepAliveError"]].Value = string.Empty;
                    EMOAppliance[props["SubscripeAlarmError"]].Value = string.Empty;
                    EMOAppliance[props["SubscripeNeDeviceError"]].Value = string.Empty;
                    //EMOAppliance[props["LatestConnectInfo"]].Value = string.Empty;

                    //EMOAppliance[props["LatestStatus"]].Value = Constants.ESightConnectionStatus.NONE;

                    ManagementPackClass baseEntity = OM12Connection.GetManagementPackClass("System.Entity");
                    EMOAppliance[baseEntity, "DisplayName"].Value = appliance.Host;
                    incrementalDiscoveryData.Add(EMOAppliance);
                    incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG);
                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
Ejemplo n.º 6
0
        private void lbOk_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //IDataItem DI = this.TemplateSoftwareTitle.sipInstance;
                //Guid CurrentNodeId = (Guid)DI["$Id$"];
                //EnterpriseManagementObject SoftwareTitle_EMO = emg.EntityObjects.GetObject<EnterpriseManagementObject>(CurrentNodeId, ObjectQueryOptions.Default);
                //MessageBox.Show(SoftwareTitle_EMO.Name);
                //MessageBox.Show(TemplateSoftwareTitle.mpClass.Name);

                if (this.txtDisplayName.Text != "" && this.txtDisplayName.Text != null)
                {
                    //ManagementPackClass classTask = ManagementGroup.EntityTypes.GetClass(“Task”, testMP)
                    CreatableEnterpriseManagementObject Version = new CreatableEnterpriseManagementObject(emg, classSoftwareVersion);
                    //Version [classTask, “Id”].Value = Guid.NewGuid().ToString();
                    Version[classSoftwareVersion, "DisplayName"].Value = this.txtDisplayName.Text;

                    CreatableEnterpriseManagementRelationshipObject relationshipObject = new CreatableEnterpriseManagementRelationshipObject(emg, relSoftwareTitleHasSoftwareVersion);
                    relationshipObject.SetSource(EMO_SoftwareTitle);
                    relationshipObject.SetTarget(Version);

                    IncrementalDiscoveryData dd = new IncrementalDiscoveryData();
                    dd.Add(Version);            //target object
                    dd.Add(relationshipObject); //relationship object
                    dd.Commit(emg);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Type SoftwareVersion DisplayName!", "Warning!!!", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show("Ok_MouseDown void error : " + ex.Message, "Service Manager", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
        }
        public async Task <Result> Update(ESightAppliance appliance)
        {
            return(await Task.Run(async() =>
            {
                try
                {
                    var obj = await this.FindByHost(appliance.Host);
                    var exsitObj = obj.Data;
                    if (exsitObj == null)
                    {
                        return Result.Failed(104, $"ESight {appliance.Host} can not find.");
                    }
                    IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData();

                    // update appliance record
                    ManagementPackClass MPClass = GetMPClass();
                    EnterpriseManagementObject managementObject = obj.Data;
                    var props = OM12Connection.GetManagementPackProperties(managementObject);
                    managementObject[props["Port"]].Value = appliance.Port;
                    managementObject[props["AliasName"]].Value = appliance.AliasName;
                    string currentSystemId = managementObject[props["SystemId"]].Value as string;
                    bool IsSystemIdChanged = currentSystemId != appliance.SystemId;
                    if (IsSystemIdChanged)
                    {
                        managementObject[props["SystemId"]].Value = appliance.SystemId;
                        managementObject[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D");
                        managementObject[props["SubKeepAliveStatus"]].Value = 0;
                        managementObject[props["SubscriptionAlarmStatus"]].Value = 0;
                        managementObject[props["SubscriptionNeDeviceStatus"]].Value = 0;
                        managementObject[props["SubKeepAliveError"]].Value = string.Empty;
                        managementObject[props["SubscripeAlarmError"]].Value = string.Empty;
                        managementObject[props["SubscripeNeDeviceError"]].Value = string.Empty;
                    }
                    if (appliance.UpdateCredential)
                    {
                        managementObject[props["LoginAccount"]].Value = appliance.LoginAccount;
                        managementObject[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance
                                                                         .EncryptForCS(appliance.LoginPassword);
                    }
                    managementObject[props["LastModifiedOn"]].Value = DateTime.UtcNow;
                    incrementalDiscoveryData.Add(managementObject);
                    incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG);
                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        private void InsertDetials(RackServer model)
        {
            try
            {
                HWLogger.GetESightSdkLogger(model.ESight).Debug($"Insert Rack:{model.DN}");
                var discoveryData = new IncrementalDiscoveryData();

                var rackServer = this.CreateRackServer(model);
                discoveryData.Add(rackServer);
                discoveryData.Commit(this.MontioringConnector);
            }
            catch (Exception e)
            {
                HWLogger.GetESightSdkLogger(model.ESight).Error($"Insert (Rack Error:{model.DN}", e);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// The update rack.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="isPolling">是否是轮询</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="Exception"></exception>
        public void UpdateRack(RackServer model, bool isPolling)
        {
            try
            {
                HWLogger.GetESightSdkLogger(model.ESight).Debug($"Start UpdateRack. [{model.DN}] [isPolling:{isPolling}]");
                var oldBlade = this.GetRackServer(model.DeviceId);
                if (oldBlade == null)
                {
                    throw new Exception($"Can not find the server:{model.DN}");
                }
                var propertys     = this.RackClass.PropertyCollection; // 获取到class的属性
                var discoveryData = new IncrementalDiscoveryData();
                oldBlade[this.DisplayNameField].Value = model.ServerName;
                if (model.Status != "-3")
                {
                    oldBlade[propertys["Status"]].Value = model.StatusTxt;
                }
                oldBlade[propertys["iBMCIPv4Address"]].Value  = model.iBMCIPv4Address;
                oldBlade[propertys["Type"]].Value             = model.Type;
                oldBlade[propertys["UUID"]].Value             = model.UUID;
                oldBlade[propertys["AveragePower"]].Value     = model.AveragePower;
                oldBlade[propertys["PeakPower"]].Value        = model.PeakPower;
                oldBlade[propertys["PowerConsumption"]].Value = model.PowerConsumption;
                oldBlade[propertys["DNSServerIP"]].Value      = model.DNSServerIP;
                oldBlade[propertys["DNSName"]].Value          = model.DNSName;


                oldBlade[propertys["ProductSn"]].Value      = model.ProductSN;
                oldBlade[propertys["HostName"]].Value       = model.HostName;
                oldBlade[propertys["CPUNums"]].Value        = model.CPUNums;
                oldBlade[propertys["CPUCores"]].Value       = model.CPUCores;
                oldBlade[propertys["CPUModel"]].Value       = model.CPUModel;
                oldBlade[propertys["MemoryCapacity"]].Value = model.MemoryCapacity;
                oldBlade[propertys["AssertTag"]].Value      = model.AssertTag;
                if (isPolling)
                {
                    oldBlade[propertys["BMCVersion"]].Value = model.BMCVersion;
                }
                oldBlade[propertys["eSight"]].Value = model.ESight;
                discoveryData.Add(oldBlade);
                discoveryData.Overwrite(this.MontioringConnector);
            }
            catch (Exception e)
            {
                HWLogger.GetESightSdkLogger(model.ESight).Error($"Update UpdateRack Error.[{model.DN}] [isPolling:{isPolling}]", e);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Adds the specified appliance.
        /// </summary>
        /// <param name="appliance">The appliance.</param>
        /// <returns>Result.</returns>
        public async Task <Result> Add(FdAppliance appliance)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    if (MGroup.Instance.Exsits(this.FdApplianceClass, $"HostIP='{appliance.HostIP}'"))
                    {
                        return Result.Failed(101, $"FusionDirector {appliance.HostIP} already exsits.");
                    }

                    var incrementalDiscoveryData = new IncrementalDiscoveryData();
                    // add appliance record

                    var emoAppliance = new CreatableEnterpriseManagementObject(MGroup.Instance, this.FdApplianceClass);
                    var props = this.FdApplianceClass.PropertyCollection;
                    emoAppliance[props["UniqueId"]].Value = FusionDirectUniqueIdPrefix + Guid.NewGuid().ToString("D");
                    emoAppliance[props["HostIP"]].Value = appliance.HostIP;
                    emoAppliance[props["AliasName"]].Value = appliance.AliasName;
                    emoAppliance[props["LoginAccount"]].Value = appliance.LoginAccount;
                    emoAppliance[props["LoginPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.LoginPd);
                    emoAppliance[props["Port"]].Value = appliance.Port;
                    emoAppliance[props["EventUserName"]].Value = appliance.EventUserName;
                    emoAppliance[props["EventPd"]].Value = RijndaelManagedCrypto.Instance.EncryptForCs(appliance.EventPd);
                    emoAppliance[props["SubscribeId"]].Value = appliance.SubscribeId;
                    emoAppliance[props["SubscribeStatus"]].Value = appliance.SubscribeStatus;
                    emoAppliance[props["LatestSubscribeInfo"]].Value = appliance.LatestSubscribeInfo;
                    emoAppliance[props["LastModifyTime"]].Value = appliance.LastModifyTime;
                    emoAppliance[props["CreateTime"]].Value = appliance.CreateTime;

                    emoAppliance[this.DisplayNameField].Value = appliance.HostIP;
                    incrementalDiscoveryData.Add(emoAppliance);

                    incrementalDiscoveryData.Commit(MGroup.Instance);
                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
        /// <summary>
        /// Inserts the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        private void Insert(Server model)
        {
            try
            {
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Server:{model.UnionId}");
                var discoveryData = new IncrementalDiscoveryData();

                #region Server

                var server = this.CreateServer(model);
                discoveryData.Add(server);

                #endregion

                discoveryData.Commit(this.MontioringConnector);
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Server Finish:{model.UnionId}");
            }
            catch (Exception e)
            {
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Insert Server Error:{model.UnionId}");
            }
        }
        /// <summary>
        /// Inserts the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        public void Insert(Enclosure model)
        {
            try
            {
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"Insert Enclosure:{model.UnionId}");
                var discoveryData = new IncrementalDiscoveryData();

                #region Enclosure

                var enclosure = this.CreateEnclosure(model);
                discoveryData.Add(enclosure);

                #endregion

                discoveryData.Commit(this.MontioringConnector);
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Debug($"InsertEnclosure finish.[{model.UnionId}]");
            }
            catch (Exception e)
            {
                HWLogger.GetFdSdkLogger(model.FusionDirectorIp).Error(e, $"Insert Enclosure Error:{model.UnionId}");
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Updates the main with out related.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void UpdateMainWithOutChildBlade(HighdensityServer model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateHighdensity WithOut ChildBoard");
            var oldBlade = this.GetHighdensityServer(model.DN);

            if (oldBlade == null)
            {
                throw new Exception($"Can not find the server:{model.DN}");
            }
            var propertys     = this.HighdensityClass.PropertyCollection; // 获取到class的属性
            var discoveryData = new IncrementalDiscoveryData();

            oldBlade[propertys["eSight"]].Value       = model.ESight;
            oldBlade[propertys["Status"]].Value       = model.Status;
            oldBlade[propertys["UUID"]].Value         = model.UUID;
            oldBlade[propertys["Vendor"]].Value       = "HUAWEI";
            oldBlade[propertys["Manufacturer"]].Value = model.Manufacturer;
            oldBlade[propertys["IPAddress"]].Value    = model.IpAddress;
            oldBlade[propertys["ProductSn"]].Value    = model.ProductSN;

            // oldBlade[propertys["ServerName"]].Value = model.ServerName;
            // oldBlade[propertys["iBMCVersion"]].Value = model.Version;
            oldBlade[this.DisplayNameField].Value = model.ServerName;
            discoveryData.Add(oldBlade);

            var fanGroup = oldBlade.GetRelatedMonitoringObjects(this.FanGroupClass).First();

            discoveryData.Add(fanGroup);

            var relatedFanObjects = fanGroup.GetRelatedMonitoringObjects(this.FanClass);
            var deleteFan         = relatedFanObjects.Where(
                x => model.FanList.All(y => y.UUID != x[this.FanClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();

            deleteFan.ForEach(x => { discoveryData.Remove(x); });
            model.FanList.ForEach(
                x =>
            {
                var fan = this.UpdateFan(x);
                if (fan == null)
                {
                    var newFan = this.CreateFan(x);
                    newFan[this.PartGroupKey].Value    = fanGroup[this.PartGroupKey].Value;
                    newFan[this.ComputerKey].Value     = model.DN;
                    newFan[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(newFan);
                }
                else
                {
                    discoveryData.Add(fan);
                }
            });

            #region PSU

            var psuGroup = oldBlade.GetRelatedMonitoringObjects(this.PowerSupplyGroupClass).First();
            discoveryData.Add(psuGroup);

            var relatedPsuObjects = psuGroup.GetRelatedMonitoringObjects(this.PowerSupplyClass);
            var deletePsu         = relatedPsuObjects.Where(
                x => model.PowerSupplyList.All(
                    y => y.UUID != x[this.PowerSupplyClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deletePsu.ForEach(x => { discoveryData.Remove(x); });

            model.PowerSupplyList.ForEach(
                x =>
            {
                var psu = this.UpdatePowerSupply(x);
                if (psu == null)
                {
                    var newpsu = this.CreatePowerSupply(x);
                    newpsu[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                    newpsu[this.ComputerKey].Value     = model.DN;
                    newpsu[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(newpsu);
                }
                else
                {
                    discoveryData.Add(psu);
                }
            });

            #endregion

            // var relatedObjects = oldBlade.GetRelatedMonitoringObjects(ChildHighdensityClass);
            // relatedObjects.ToList().ForEach(x => discoveryData.Add(x));
            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("End UpdateHighdensity WithOut ChildBoard");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// The update child blade.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <exception cref="Exception">Can not find the child blade server</exception>
        public void UpdateChildBoard(ChildHighdensity model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateChildBoard");
            var oldObject = this.GetObject($"DN = '{model.DN}'", this.ChildHighdensityClass);

            if (oldObject == null)
            {
                throw new Exception($"Can not find the child blade server:{model.DN}");
            }
            var propertys = this.ChildHighdensityClass.PropertyCollection; // 获取到class的属性

            var discoveryData = new IncrementalDiscoveryData();

            var childHighdensityKey = this.ChildHighdensityClass.PropertyCollection["DN"];

            oldObject[propertys["Status"]].Value    = model.Status;
            oldObject[propertys["IPAddress"]].Value = model.IpAddress;
            oldObject[propertys["UUID"]].Value      = model.UUID;
            oldObject[propertys["ProductSn"]].Value = model.ProductSn;
            oldObject[propertys["Type"]].Value      = model.Type;

            oldObject[this.DisplayNameField].Value = model.Name;
            discoveryData.Add(oldObject);

            #region CPU

            var cpuGroup = oldObject.GetRelatedMonitoringObjects(this.CpuGroupClass).First();
            discoveryData.Add(cpuGroup);

            var relatedCpuObjects = cpuGroup.GetRelatedMonitoringObjects(this.CpuClass);
            var deleteCpu         = relatedCpuObjects.Where(
                x => model.CPUList.All(y => y.UUID != x[this.CpuClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();
            deleteCpu.ForEach(x => { discoveryData.Remove(x); });
            model.CPUList.ForEach(
                y =>
            {
                var cpu = this.UpdateCpu(y);
                if (cpu == null)
                {
                    var newCpu = this.CreateCpu(y);
                    newCpu[this.PartChildGroupKey].Value = cpuGroup[this.PartChildGroupKey].Value;
                    newCpu[childHighdensityKey].Value    = model.DN;
                    newCpu[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newCpu[this.ComputerKey].Value       = model.DN;
                    newCpu[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newCpu);
                }
                else
                {
                    discoveryData.Add(cpu);
                }
            });

            #endregion

            #region Memory

            var memoryGroup = oldObject.GetRelatedMonitoringObjects(this.MemoryGroupClass).First();
            discoveryData.Add(memoryGroup);

            var relatedMemoryObjects = memoryGroup.GetRelatedMonitoringObjects(this.MemoryClass);
            var deleteMemory         = relatedMemoryObjects.Where(
                x => model.MemoryList.All(
                    y => y.UUID != x[this.MemoryClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deleteMemory.ForEach(x => { discoveryData.Remove(x); });
            model.MemoryList.ForEach(
                y =>
            {
                var memory = this.UpdateMemory(y);
                if (memory == null)
                {
                    var newMemory = this.CreateMemory(y);
                    newMemory[this.PartChildGroupKey].Value = memoryGroup[this.PartChildGroupKey].Value;
                    newMemory[childHighdensityKey].Value    = model.DN;
                    newMemory[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newMemory[this.ComputerKey].Value       = model.DN;
                    newMemory[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newMemory);
                }
                else
                {
                    discoveryData.Add(memory);
                }
            });

            #endregion

            #region Disk

            var diskGroup = oldObject.GetRelatedMonitoringObjects(this.DiskGroupClass).First();
            discoveryData.Add(diskGroup);

            var relatedDiskObjects = diskGroup.GetRelatedMonitoringObjects(this.DiskClass);
            var deleteDisk         = relatedDiskObjects.Where(
                x => model.DiskList.All(
                    y => y.UUID != x[this.DiskClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteDisk.ForEach(x => { discoveryData.Remove(x); });
            model.DiskList.ForEach(
                y =>
            {
                var disk = this.UpdateDisk(y);
                if (disk == null)
                {
                    var newDisk = this.CreateDisk(y);
                    newDisk[this.PartChildGroupKey].Value = diskGroup[this.PartChildGroupKey].Value;
                    newDisk[childHighdensityKey].Value    = model.DN;
                    newDisk[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newDisk[this.ComputerKey].Value       = model.DN;
                    newDisk[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newDisk);
                }
                else
                {
                    discoveryData.Add(disk);
                }
            });

            #endregion

            #region Raid

            var raidGroup = oldObject.GetRelatedMonitoringObjects(this.RaidGroupClass).First();
            discoveryData.Add(raidGroup);

            var relatedRaidObjects = raidGroup.GetRelatedMonitoringObjects(this.RaidClass);
            var deleteRaid         = relatedRaidObjects.Where(
                x => model.RaidList.All(
                    y => y.UUID != x[this.RaidClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteRaid.ForEach(x => { discoveryData.Remove(x); });
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.UpdateRaidControl(y);
                if (raid == null)
                {
                    var newRaid = this.CreateRaidControl(y);
                    newRaid[this.PartChildGroupKey].Value = raidGroup[this.PartChildGroupKey].Value;
                    newRaid[childHighdensityKey].Value    = model.DN;
                    newRaid[this.PartGroupKey].Value      = oldObject[this.PartGroupKey].Value;
                    newRaid[this.ComputerKey].Value       = model.DN;
                    newRaid[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(newRaid);
                }
                else
                {
                    discoveryData.Add(raid);
                }
            });

            #endregion

            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("End UpdateChildBoard");
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void InsertDetials(HighdensityServer model)
        {
            var discoveryData = new IncrementalDiscoveryData();

            var baseComputer = this.GetComputerByDn(model.DN);

            if (baseComputer == null)
            {
                var newBaseComputer = this.CreateComputer(model.DN);
                discoveryData.Add(newBaseComputer);
            }
            else
            {
                discoveryData.Add(baseComputer);
            }
            #region HighdensityServer

            var highdensityServer = this.CreateHighdensityServer(model);
            highdensityServer[this.HuaweiServerKey].Value = model.DN;

            discoveryData.Add(highdensityServer);

            #endregion

            #region Fan

            var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DN);
            discoveryData.Add(fanGroup);
            model.FanList.ForEach(
                x =>
            {
                var fan = this.CreateFan(x);
                fan[this.PartGroupKey].Value    = fanGroup[this.PartGroupKey].Value;
                fan[this.ComputerKey].Value     = model.DN;
                fan[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(fan);
            });

            #endregion

            #region PSU

            var psuGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DN);
            discoveryData.Add(psuGroup);
            model.PowerSupplyList.ForEach(
                x =>
            {
                var powerSupply = this.CreatePowerSupply(x);
                powerSupply[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                powerSupply[this.ComputerKey].Value     = model.DN;
                powerSupply[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(powerSupply);
            });

            #endregion

            #region Child Highdensity

            var childHighdensityGroup    = this.CreateLogicalGroup(this.ChildHighdensityGroupClass, model.DN);
            var childHighdensityGroupKey = childHighdensityGroup[this.PartGroupKey].Value.ToString();
            discoveryData.Add(childHighdensityGroup);
            model.ChildHighdensitys.ForEach(
                x =>
            {
                var childHighdensity = this.CreateChildHighdensity(x);
                childHighdensity[this.PartGroupKey].Value    = childHighdensityGroupKey;
                childHighdensity[this.ComputerKey].Value     = model.DN;
                childHighdensity[this.HuaweiServerKey].Value = model.DN;
                discoveryData.Add(childHighdensity);
                var childHighdensityKey = this.ChildHighdensityClass.PropertyCollection["DN"];

                #region CPU

                var cpuGroup = this.CreateLogicalChildGroup(this.CpuGroupClass, model.DN, x.DN);

                cpuGroup[childHighdensityKey].Value = x.DN;
                cpuGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                discoveryData.Add(cpuGroup);
                x.CPUList.ForEach(
                    y =>
                {
                    var cpu = this.CreateCpu(y);
                    cpu[this.PartChildGroupKey].Value = cpuGroup[this.PartChildGroupKey].Value;
                    cpu[childHighdensityKey].Value    = x.DN;
                    cpu[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    cpu[this.ComputerKey].Value       = model.DN;
                    cpu[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(cpu);
                });

                #endregion

                #region Memory

                var memoryGroup = this.CreateLogicalChildGroup(this.MemoryGroupClass, model.DN, x.DN);
                memoryGroup[childHighdensityKey].Value = x.DN;
                memoryGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                discoveryData.Add(memoryGroup);
                x.MemoryList.ForEach(
                    y =>
                {
                    var memory = this.CreateMemory(y);
                    memory[this.PartChildGroupKey].Value =
                        memoryGroup[this.PartChildGroupKey].Value;
                    memory[childHighdensityKey].Value  = x.DN;
                    memory[this.PartGroupKey].Value    = childHighdensityGroupKey;
                    memory[this.ComputerKey].Value     = model.DN;
                    memory[this.HuaweiServerKey].Value = model.DN;
                    discoveryData.Add(memory);
                });

                #endregion

                #region Disk

                var diskGroup = this.CreateLogicalChildGroup(this.DiskGroupClass, model.DN, x.DN);
                diskGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                diskGroup[childHighdensityKey].Value = x.DN;
                discoveryData.Add(diskGroup);
                x.DiskList.ForEach(
                    y =>
                {
                    var disk = this.CreateDisk(y);
                    disk[this.PartChildGroupKey].Value = diskGroup[this.PartChildGroupKey].Value;
                    disk[childHighdensityKey].Value    = x.DN;
                    disk[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    disk[this.ComputerKey].Value       = model.DN;
                    disk[this.HuaweiServerKey].Value   = model.DN;
                    discoveryData.Add(disk);
                });

                #endregion

                #region Raid

                var raidGroup = this.CreateLogicalChildGroup(this.RaidGroupClass, model.DN, x.DN);
                raidGroup[this.PartGroupKey].Value   = childHighdensityGroupKey;
                raidGroup[childHighdensityKey].Value = x.DN;
                discoveryData.Add(raidGroup);
                x.RaidList.ForEach(
                    y =>
                {
                    var raid = this.CreateRaidControl(y);
                    raid[this.PartChildGroupKey].Value = raidGroup[this.PartChildGroupKey].Value;
                    raid[childHighdensityKey].Value    = x.DN;
                    raid[this.PartGroupKey].Value      = childHighdensityGroupKey;
                    raid[this.HuaweiServerKey].Value   = model.DN;
                    raid[this.ComputerKey].Value       = model.DN;
                    discoveryData.Add(raid);
                });

                #endregion
            });

            #endregion

            if (!this.ExsitsHighdensityServer(model.DN))
            {
                discoveryData.Commit(this.MontioringConnector);
            }
            else
            {
                discoveryData.Overwrite(this.MontioringConnector);
            }
        }
Ejemplo n.º 16
0
        private void NewDestinationDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.None && DialogResult == DialogResult.OK)
            {
                string fqdnValue        = tbFQDN.Text;
                int    targetIndexValue = 0;
                if (cbAllowDuplicates.Checked || ExistingObject != null) // for existing object always use existing index value, which was loaded into nudTargetIndex in the constructor
                {
                    targetIndexValue = Convert.ToInt32(nudTargetIndex.Value);
                }
                object selectedMAP = null;
                if (rbPool.Checked)
                {
                    selectedMAP = cbResourcePools.SelectedItem;
                }
                if (rbAgent.Checked)
                {
                    selectedMAP = lbAgentList.SelectedItem;
                }
                if (selectedMAP is MonitoringObject mo)
                {
                    tbMAPDetails.Text = $"{mo.DisplayName ?? "N/A"} of {mo.GetType().Name}";
                }
                else
                {
                    tbMAPDetails.Text = $"{selectedMAP?.ToString() ?? "NULL"} of {selectedMAP?.GetType().Name ?? "N/A"}";
                }

                // basic preliminary checks
                if (string.IsNullOrWhiteSpace(fqdnValue))
                {
                    MessageBox.Show("FQDN value cannot be empty.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
                bool ipResolved;
                try
                {
                    IPAddress[] ipList = Dns.GetHostAddresses(fqdnValue);
                    if (ipList == null || ipList.Length == 0)
                    {
                        ipResolved = false;
                    }
                    else
                    {
                        ipResolved = true;
                    }
                }
                catch
                {
                    ipResolved = false;
                }
                if (!ipResolved)
                {
                    if (MessageBox.Show("FQDN is specified, but cannot be resolved into an IP address in the current location, i.e. at the machine where SCOM Console application is running. However, the selected action point might be able to resolve it.\r\nContinue or cancel?", "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                if (selectedMAP == null)
                {
                    MessageBox.Show("Select an agent or a resource pool, which is to handle tests for the destination.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }

                // Scenarios: 1) new object 2) edit object 3) move object to a new MAP/HS 4) 2 + 3
                #region New Object
                if (ExistingObjectId == Guid.Empty)
                {
                    // try to find an existing object, to avoid update instead of insert/add

                    if (IsFQDNClassInstanceExists(fqdnValue, targetIndexValue))
                    {
                        if (cbAllowDuplicates.Checked)
                        {
                            if (MessageBox.Show("Duplicates are allowed, but a duplicate with the same target index already exists.\r\nFind another index automatically?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                int newIndex = 0;
                                while (IsFQDNClassInstanceExists(fqdnValue, newIndex))
                                {
                                    newIndex++;
                                }
                                targetIndexValue     = newIndex;
                                nudTargetIndex.Value = newIndex;
                            }
                            else
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show("This destination already exists.\r\nSelect 'Allow duplicates' to create a duplicate destination, or reuse the existing destination to add tests.", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            e.Cancel = true;
                            return;
                        }
                    }

                    // finally, trying to create a new destination
                    try
                    {
                        IncrementalDiscoveryData                        incrementalDiscovery             = new IncrementalDiscoveryData();
                        CreatableEnterpriseManagementObject             newInstance                      = new CreatableEnterpriseManagementObject(ManagementGroup, fqdnClass);
                        CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;

                        newInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = string.IsNullOrEmpty(tbDisplayName.Text) ? fqdnValue : tbDisplayName.Text;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = fqdnValue;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = targetIndexValue;
                        newInstance[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value = string.IsNullOrEmpty(tbDescription.Text) ? "" : tbDescription.Text;

                        if (rbAgent.Checked)
                        {
                            newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relHealthServiceShouldManageEntiry);
                        }
                        if (rbPool.Checked)
                        {
                            newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relResourcePoolShouldManageEntity);
                        }
                        newSomethingShouldManageInstance?.SetTarget(newInstance);
                        newSomethingShouldManageInstance?.SetSource(selectedMAP as MonitoringObject);

                        incrementalDiscovery.Add(newInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            incrementalDiscovery.Add(newSomethingShouldManageInstance);
                        }

                        EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                        incrementalDiscovery.Commit(connector);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Failed to create new destination.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.Cancel = true;
                        return;
                    }

                    // END SCENARIO #1
                    return;
                }
                #endregion
                #region Update Object details
                if (ExistingObject != null)
                {
                    bool objectChanged = false;
                    objectChanged = objectChanged || (ExistingObject[SystemId.EntityClassProperties.DisplayNamePropertyId].Value?.ToString() != tbDisplayName.Text);
                    // immutable: objectChanged = objectChanged || (ExistingObject[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value?.ToString() != fqdnValue);
                    objectChanged = objectChanged || (ExistingObject[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value?.ToString() != tbDescription.Text);
                    // TargetIndex cannot be changed for existing objects
                    if (objectChanged)
                    {
                        try
                        {
                            IncrementalDiscoveryData            incrementalDiscovery = new IncrementalDiscoveryData();
                            CreatableEnterpriseManagementObject modifiedInstance     = new CreatableEnterpriseManagementObject(ManagementGroup, fqdnClass);

                            modifiedInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = string.IsNullOrEmpty(tbDisplayName.Text) ? "" : tbDisplayName.Text;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.FullyQualifiedDomainNamePropertyId].Value = fqdnValue;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.TargetIndexPropertyId].Value = targetIndexValue;
                            modifiedInstance[IDs.FullyQualifiedDomainNameClassProperties.DescriptionPropertyId].Value = string.IsNullOrEmpty(tbDescription.Text) ? "" : tbDescription.Text;

                            incrementalDiscovery.Add(modifiedInstance);
                            EnterpriseManagementConnector connector = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                            incrementalDiscovery.Overwrite(connector);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Failed to update the destination details.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                #endregion
                #region Move object servicing point
                if (ExistingObject != null)
                {
                    IEnumerable <MonitoringObject> currentActionPoints = FindActionPoints(ExistingObject);
                    if (currentActionPoints.Any() && HasMAPChanged(currentActionPoints.First()))
                    {
                        try
                        {
                            MonitoringObject newMAP = selectedMAP as MonitoringObject;
                            // remove all existing SHOULD-relations
                            EnterpriseManagementConnector connector        = ManagementGroup.ConnectorFramework.GetMonitoringConnector();
                            IncrementalDiscoveryData      RemovalDiscovery = new IncrementalDiscoveryData();
                            bool commitOverwrite = false;
                            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allMAPRelations = ManagementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(ExistingObject.Id, relResourcePoolShouldManageEntity, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
                            IEnumerable <EnterpriseManagementRelationshipObject <EnterpriseManagementObject> > allHSRelations  = ManagementGroup.EntityObjects.GetRelationshipObjectsWhereTarget <EnterpriseManagementObject>(ExistingObject.Id, relHealthServiceShouldManageEntiry, DerivedClassTraversalDepth.Recursive, TraversalDepth.OneLevel, ObjectQueryOptions.Default).Where(x => !x.IsDeleted);
                            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allMAPRelations)
                            {
                                if (rel.SourceObject.Id != newMAP.Id)
                                {
                                    // remove this relationship
                                    RemovalDiscovery.Remove(rel);
                                    commitOverwrite = true;
                                }
                            }
                            foreach (EnterpriseManagementRelationshipObject <EnterpriseManagementObject> rel in allHSRelations)
                            {
                                if (rel.SourceObject.Id != newMAP.Id)
                                {
                                    // remove this relationship
                                    RemovalDiscovery.Remove(rel);
                                    commitOverwrite = true;
                                }
                            }
                            if (commitOverwrite)
                            {
                                RemovalDiscovery.Overwrite(connector);
                            }

                            // add the new relationship
                            IncrementalDiscoveryData incrementalDiscovery = new IncrementalDiscoveryData();
                            CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;
                            if (rbAgent.Checked)
                            {
                                newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relHealthServiceShouldManageEntiry);
                            }
                            if (rbPool.Checked)
                            {
                                newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(ManagementGroup, relResourcePoolShouldManageEntity);
                            }
                            newSomethingShouldManageInstance?.SetTarget(ExistingObject);
                            newSomethingShouldManageInstance?.SetSource(newMAP);

                            if (newSomethingShouldManageInstance != null)
                            {
                                incrementalDiscovery.Add(newSomethingShouldManageInstance);
                            }

                            incrementalDiscovery.Commit(connector);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"Failed to update destination's management action point.\r\nError: {ex.Message}", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                            return;
                        }
                    }
                }
                #endregion
            }
        }
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                //System.Threading.Thread.Sleep(10000); //makes debugging easier.
                if (ConnectorId == null)
                {
                    throw new ArgumentNullException("ConnectorId is null.");
                }

                startTime = DateTime.UtcNow; //set the start time.

                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle)) //check if WF account is non-admin
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                #region Setup connection to EMG and get objects.
                emg = new EnterpriseManagementGroup("localhost");

                setEnterpriseManagementObjects();

                //get the last run date time so we can get projects with a last modified date greater than the last run. Check for UTC on project...
                DateTime lastRun = emoStatus[null, "LastRunFinishTime"].Value == null ? DateTime.MinValue : (DateTime)emoStatus[null, "LastRunFinishTime"].Value;

                //check to see if retention is enabled.  If so, and this is the first run, change the lastRun date.
                var retentionEnabled = emoSettings[null, "IsRetentionEnabled"].Value == null ? false : (bool)emoSettings[null, "IsRetentionEnabled"].Value;
                if (retentionEnabled && DateTime.Equals(lastRun, DateTime.MinValue))
                {
                    lastRun = DateTime.Now.AddDays(-(Convert.ToDouble(emoSettings[null, "RetentionDays"].Value)));
                }

                //set the start time on the status object.
                emoStatus[null, "LastRunStartTime"].Value  = startTime;
                emoStatus[null, "LastRunFinishTime"].Value = null;
                emoStatus[null, "Status"].Value            = mpeSyncStatusEnums.First(mpe => mpe.Name == "Microsoft.SystemCenter.LinkingFramework.SyncStatusEnum.Running");
                emoStatus[null, "MinValue"].Value          = 0;
                emoStatus[null, "MaxValue"].Value          = 100;
                #endregion

                #region Get connector credentails
                NetworkCredential creds = NetworkCredentialsHelper.GetProjectCredentials(emoConnector[null, "RunAsAccount"].Value.ToString(), emoConnector[null, "Id"].ToString(), emg.Name);
                #endregion

                EventLog.WriteEntry(strEventLogTitle, string.Format("Starting Project CI sync from Project Server...\r\n\r\nProject Server: {0}\r\nUser Name: {1}", emoConnector[null, "ProjectServerURL"].Value.ToString(), creds.Domain + "\\" + creds.UserName));

                #region license check
                var licenseExpiration = checkLicense(); //method will throw an exception if no license exists.
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));
                #endregion

                #region Connect to Project Server and read data
                ProjectConnector projectConnector = new ProjectConnector(emoConnector[null, "ProjectServerURL"].Value.ToString(), creds);
                projectConnector.Connect();

                #endregion

                #region Read data from Project Server

                if (lastRun == DateTime.MinValue)
                {
                    EventLog.WriteEntry(strEventLogTitle, "Querying Project Server for a full list of projects...");
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Querying Project Server for Projects created or modified since: {0} UTC...", lastRun));
                }

                projectConnector.LoadProjects(lastRun);

                #endregion

                #region Write data to the Service Manager DB.

                totalToProcess = projectConnector.Projects.Count();
                if (totalToProcess > 0)
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("Processing {0} projects returned from Project Server...", totalToProcess), EventLogEntryType.Information, 0);

                    iddObjects = new IncrementalDiscoveryData();
                    List <Exception> exceptionsList = new List <Exception>();

                    foreach (PublishedProject project in projectConnector.Projects)
                    {
                        try
                        {
                            projectConnector.LoadProjectTaskData(project);
                            projectConnector.LoadProjectMetaData(project);

                            iddObjects.Add(buildProjectCI(project, mpcClasses.First(c => c.Name == "Cireson.ProjectAutomation.Project")));
                        }
                        catch (EnterpriseManagementException ex)
                        {
                            exceptionsList.Add(new ProjectImportException(string.Format("An error occured while importing the following project:\r\n\r\nProject Name: {0}\r\n{1}\r\n", project.Name, ex)));
                            hasImportFailure = true;
                        }
                        //catch SP exceptions
                        finally
                        {
                            totalProcessed++;
                            updateWorkflowStatus(false, ((totalProcessed * 100) / totalToProcess));
                        }
                    }//end of foreach.

                    #endregion

                    //commit the changes to the database
                    iddObjects.Overwrite(emg);

                    if (exceptionsList.Count > 0)
                    {
                        throw new AggregateException(string.Format("{0} projects failed to sync. ", (totalToProcess - exceptionsList.Count).ToString()), exceptionsList);
                    }
                    else
                    {
                        EventLog.WriteEntry(strEventLogTitle, string.Format("{0} projects successfully committed.  Elapsed Time: {1} seconds.", totalProcessed, getRunTime(startTime).Seconds), EventLogEntryType.Information, 0);
                    }
                }
                else
                {
                    EventLog.WriteEntry(strEventLogTitle, string.Format("No updated projects exist.  Project Connector workflow is exiting.  Elapsed Time: {0} seconds.", getRunTime(startTime).Seconds));
                }
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format(ex.Message + "Elapsed Time: {0} seconds. The following projects failed to sync: \r\n\r\n{1}", getRunTime(startTime).Seconds, exceptionStrings.ToString()), EventLogEntryType.Error, 1);
                hasImportFailure = true;
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            catch (Exception ex)
            {
                TrackData(ex.Message);
                EventLog.WriteEntry(strEventLogTitle, string.Format(strExceptionMessage, ex.Message, ex.InnerException, ex.StackTrace, ex.Source), EventLogEntryType.Error, 1);
                hasImportFailure = true;
                throw;
            }
            finally
            {
                updateWorkflowStatus(true, 100);

                if (emg != null)
                {
                    emg.Dispose();
                }
            }
            return(ActivityExecutionStatus.Closed);
        }
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        private void InsertDetials(KunLunServer model)
        {
            try
            {
                HWLogger.GetESightSdkLogger(model.ESight).Debug($"Insert KunLun:{model.DN}");
                var discoveryData = new IncrementalDiscoveryData();

                #region KunLunServer

                var kunLunServer = this.CreateKunLunServer(model);
                discoveryData.Add(kunLunServer);

                #endregion

                #region Fan

                var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DeviceId);
                discoveryData.Add(fanGroup);
                model.FanList.ForEach(
                    x =>
                {
                    var fan = this.CreateFan(x);
                    fan[this.PartGroupKey].Value = fanGroup[this.PartGroupKey].Value;

                    fan[this.HuaweiServerKey].Value = model.DeviceId;

                    discoveryData.Add(fan);
                });

                #endregion

                #region PSU

                var powerSupplyGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DeviceId);
                discoveryData.Add(powerSupplyGroup);
                model.PowerSupplyList.ForEach(
                    x =>
                {
                    var powerSupply = this.CreatePowerSupply(x);
                    powerSupply[this.PartGroupKey].Value    = powerSupplyGroup[this.PartGroupKey].Value;
                    powerSupply[this.HuaweiServerKey].Value = model.DeviceId;

                    discoveryData.Add(powerSupply);
                });

                #endregion

                #region Raid

                var raidGroup = this.CreateLogicalGroup(this.RaidGroupClass, model.DeviceId);
                discoveryData.Add(raidGroup);
                model.RaidList.ForEach(
                    y =>
                {
                    var raid = this.CreateRaidControl(y);
                    raid[this.PartGroupKey].Value    = raidGroup[this.PartGroupKey].Value;
                    raid[this.HuaweiServerKey].Value = model.DeviceId;

                    discoveryData.Add(raid);
                });

                #endregion

                #region Disk

                var diskGroup = this.CreateLogicalGroup(this.PhysicalDiskGroupClass, model.DeviceId);
                discoveryData.Add(diskGroup);
                model.DiskList.ForEach(
                    x =>
                {
                    var disk = this.CreateDisk(x);
                    disk[this.PartGroupKey].Value    = diskGroup[this.PartGroupKey].Value;
                    disk[this.HuaweiServerKey].Value = model.DeviceId;

                    discoveryData.Add(disk);
                });

                #endregion

                discoveryData.Commit(this.MontioringConnector);
            }
            catch (Exception e)
            {
                HWLogger.GetESightSdkLogger(model.ESight).Error($"Insert KunLun Error:{model.DN}", e);
            }
        }
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void InsertDetials(KunLunServer model)
        {
            var discoveryData = new IncrementalDiscoveryData();

            var baseComputer = this.GetComputerByDn(model.DN);

            if (baseComputer == null)
            {
                var newBaseComputer = this.CreateComputer(model.DN);
                discoveryData.Add(newBaseComputer);
            }
            else
            {
                discoveryData.Add(baseComputer);
            }

            #region KunLunServer

            var kunLunServer = this.CreateKunLunServer(model);
            kunLunServer[this.ComputerKey].Value = model.DN;
            discoveryData.Add(kunLunServer);

            #endregion

            #region Fan

            var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DN);
            discoveryData.Add(fanGroup);
            model.FanList.ForEach(
                x =>
            {
                var fan = this.CreateFan(x);
                fan[this.PartGroupKey].Value = fanGroup[this.PartGroupKey].Value;

                fan[this.HuaweiServerKey].Value = model.DN;
                fan[this.ComputerKey].Value     = model.DN;
                discoveryData.Add(fan);
            });

            #endregion

            #region PSU

            var powerSupplyGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DN);
            discoveryData.Add(powerSupplyGroup);
            model.PowerSupplyList.ForEach(
                x =>
            {
                var powerSupply = this.CreatePowerSupply(x);
                powerSupply[this.PartGroupKey].Value    = powerSupplyGroup[this.PartGroupKey].Value;
                powerSupply[this.HuaweiServerKey].Value = model.DN;
                powerSupply[this.ComputerKey].Value     = model.DN;
                discoveryData.Add(powerSupply);
            });

            #endregion

            #region Raid

            var raidGroup = this.CreateLogicalGroup(this.RaidGroupClass, model.DN);
            discoveryData.Add(raidGroup);
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.CreateRaidControl(y);
                raid[this.PartGroupKey].Value    = raidGroup[this.PartGroupKey].Value;
                raid[this.HuaweiServerKey].Value = model.DN;
                raid[this.ComputerKey].Value     = model.DN;
                discoveryData.Add(raid);
            });

            #endregion

            #region Disk

            var diskGroup = this.CreateLogicalGroup(this.PhysicalDiskGroupClass, model.DN);
            discoveryData.Add(diskGroup);
            model.DiskList.ForEach(
                x =>
            {
                var disk = this.CreateDisk(x);
                disk[this.PartGroupKey].Value    = diskGroup[this.PartGroupKey].Value;
                disk[this.HuaweiServerKey].Value = model.DN;
                disk[this.ComputerKey].Value     = model.DN;
                discoveryData.Add(disk);
            });

            #endregion

            if (!this.ExsitsKunLunServer(model.DN))
            {
                discoveryData.Commit(this.MontioringConnector);
            }
            else
            {
                discoveryData.Overwrite(this.MontioringConnector);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Add Device To Incremental Discovery Data
        /// </summary>
        /// <param name="dev"></param>
        private static void AddDeviceToIncrementalDiscoveryData(f5Device dev)
        {
            // Add Device to Discovery Data
            incrementalDiscoveryData.Add(dev.SCOM_Object_Device);

            // Add Failover State and Relationship to Discovery Data
            incrementalDiscoveryData.Add(dev.SCOM_Object_FailoverState);

            // Add Memory and Relationship to Discovery Data
            incrementalDiscoveryData.Add(dev.SCOM_Object_Memory);

            // Add Fans and Relationships to Discovery Data
            if (dev.Fans.Count > 0)
            {
                // Add FansGroup and Relationship
                incrementalDiscoveryData.Add(dev.SCOM_Object_FanGroup);
                foreach (Fan f in dev.Fans)
                {
                    // Add Fan and Relationship
                    incrementalDiscoveryData.Add(f.SCOM_Object_Fan);
                }
            }

            // Add PowerSupplies and Relationships to Discovery Data
            if (dev.PowerSupplies.Count > 0)
            {
                // Add PowerSuppliesGroup and Relationship
                incrementalDiscoveryData.Add(dev.SCOM_Object_PowerSupplyGroup);
                foreach (PowerSupply p in dev.PowerSupplies)
                {
                    // Add PowerSupply and Relationship
                    incrementalDiscoveryData.Add(p.SCOM_Object_PowerSupply);
                }
            }

            // Add Processors
            if (dev.Processors.Count > 0)
            {
                // Add ProcessorsGroup and Relationship
                incrementalDiscoveryData.Add(dev.SCOM_Object_ProcessorGroup);
                foreach (Processor p in dev.Processors)
                {
                    // Add Processor and Relationship
                    incrementalDiscoveryData.Add(p.SCOM_Object_Processor);
                }
            }

            // Add Temperature Sensors
            if (dev.TempSensors.Count > 0)
            {
                // Add Temp Sensors Group and Relationship
                incrementalDiscoveryData.Add(dev.SCOM_Object_TempSensorsGroup);
                // Add Temperature Sensors
                foreach (TempSensor t in dev.TempSensors)
                {
                    incrementalDiscoveryData.Add(t.SCOM_Object_TempSensor);
                }
            }

            // Add Disk Partitions and Relationships to Discovery Data
            if (dev.DiskPartitions.Count > 0)
            {
                // Add Disk partitions Group to Discovery Data
                incrementalDiscoveryData.Add(dev.SCOM_Object_DiskPartitionGroup);
                // Add Disk Partitions
                foreach (DiskPartition disk in dev.DiskPartitions)
                {
                    incrementalDiscoveryData.Add(disk.SCOM_Object_DiskPartition);
                }
            }
        }
Ejemplo n.º 21
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                if (RetentionDays == 0)
                {
                    throw new ArgumentNullException("No retention days set.");
                }

                //setup event log access
                if (!EventLog.SourceExists(strEventLogTitle))
                {
                    EventLog.CreateEventSource(strEventLogTitle, "Operations Manager");
                }

                EventLog.WriteEntry(strEventLogTitle, "Starting Project CI grooming...");

                emg = new EnterpriseManagementGroup("localhost");

                var licenseExpiration = checkLicense(); //method will throw an exception if no license exists.
                EventLog.WriteEntry(strEventLogTitle, string.Format("License Expiration: {0}", licenseExpiration));

                //Cireson Project (Cireson.ProjectAutomation.Library) (Cireson.ProjectAutomation.Project) (dabf07ea-6047-b6d7-f8d3-e88ac1d260e9)
                ManagementPackClass mpcProject = emg.EntityTypes.GetClass(new Guid("dabf07ea-6047-b6d7-f8d3-e88ac1d260e9"));

                var oldProjects = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(new EnterpriseManagementObjectCriteria(
                                                                                                     "LastModified < '" + DateTime.Now.AddDays(-RetentionDays).ToUniversalTime() + "'", mpcProject), ObjectQueryOptions.Default);
                IncrementalDiscoveryData iddDeletePending = new IncrementalDiscoveryData();

                EventLog.WriteEntry("Checking for Project CIs with a last modified date older than: {0}", DateTime.Now.AddDays(-RetentionDays).ToUniversalTime().ToString());

                //get PendingDelete enum
                //Pending Delete (System.Library) (System.ConfigItem.ObjectStatusEnum.PendingDelete) (47101e64-237f-12c8-e3f5-ec5a665412fb)
                var pendingDelete = emg.EntityTypes.GetEnumeration(new Guid("47101e64-237f-12c8-e3f5-ec5a665412fb"));

                exceptionsList = new List <Exception>();

                foreach (EnterpriseManagementObject project in oldProjects)
                {
                    try
                    {
                        project[null, "ObjectStatus"].Value = pendingDelete;
                        iddDeletePending.Add(project);
                    }
                    catch (EnterpriseManagementException ex)
                    {
                        exceptionsList.Add(new ProjectCIGroomingException(string.Format("Failed to set 'Pending Delete' object status on {0}.", project.Name), ex));
                    }
                }

                iddDeletePending.Overwrite(emg);

                if (exceptionsList.Count > 0)
                {
                    throw new AggregateException("One or more errors occured grooming Project CIs.", exceptionsList);
                }
            }
            catch (AggregateException ex)
            {
                TrackData(ex.Message);

                StringBuilder exceptionStrings = new StringBuilder();
                foreach (var innerEx in ex.InnerExceptions)
                {
                    exceptionStrings.AppendLine(string.Format(strExceptionMessage, innerEx.Message, innerEx.InnerException, innerEx.StackTrace, innerEx.Source));
                }

                EventLog.WriteEntry(strEventLogTitle, string.Format(ex.Message + "\r\n\r\n" + "The following projects failed:\r\n\r\n" + exceptionStrings.ToString()));
            }
            catch (EnterpriseManagementException ex)
            {
                TrackData(ex);
                TrackData(ex.Message);
                throw;
            }
            finally
            {
                if (emg != null)
                {
                    emg.Dispose();
                }
            }

            return(ActivityExecutionStatus.Closed);
        }
        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="isPolling">if set to <c>true</c> [is polling].</param>
        /// <exception cref="System.Exception"></exception>
        public void Sync(Appliance model, bool isPolling)
        {
            try
            {
                HWLogger.Service.Debug($"Start UpdateAppliance. [isPolling:{isPolling}]");
                var devices        = MGroup.Instance.EntityObjects.GetObjectReader <MonitoringObject>(ApplianceClass, ObjectQueryOptions.Default).ToList();
                var exsitAppliance = devices.FirstOrDefault();
                if (exsitAppliance == null)
                {
                    throw new Exception($"Can not find the Appliance ");
                }
                var discoveryData = new IncrementalDiscoveryData();
                this.UpdateAppliance(model, exsitAppliance);
                discoveryData.Add(exsitAppliance);

                #region EnclosureCollection
                var enclosureCollections = exsitAppliance.GetRelatedMonitoringObjects(this.EnclosureCollectionClass);
                if (enclosureCollections.Any())
                {
                    var exsit = enclosureCollections.First();
                    this.UpdateEnclosureCollection(model.EnclosureCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var enclosureCollection = this.CreateEnclosureCollection(model.EnclosureCollection);
                    discoveryData.Add(enclosureCollection);
                }
                #endregion

                #region ServerCollection
                var serverCollections = exsitAppliance.GetRelatedMonitoringObjects(this.ServerCollectionClass);
                if (serverCollections.Any())
                {
                    var exsit = serverCollections.First();
                    this.UpdateServerCollection(model.ServerCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var serverCollection = this.CreateServerCollection(model.ServerCollection);
                    discoveryData.Add(serverCollection);
                }
                #endregion

                #region EventCollection
                var eventCollections = exsitAppliance.GetRelatedMonitoringObjects(this.EventCollectionClass);
                if (eventCollections.Any())
                {
                    var exsit = eventCollections.First();
                    this.UpdateEventCollection(model.EventCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var eventCollection = this.CreateEventCollection(model.EventCollection);
                    discoveryData.Add(eventCollection);
                }
                #endregion

                #region PerformanceCollection
                var performanceCollections = exsitAppliance.GetRelatedMonitoringObjects(this.PerformanceCollectionClass);
                if (performanceCollections.Any())
                {
                    var exsit = performanceCollections.First();
                    this.UpdatePerformanceCollection(model.PerformanceCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var performanceCollection = this.CreatePerformanceCollection(model.PerformanceCollection);
                    discoveryData.Add(performanceCollection);
                }
                #endregion

                #region FusionDirectorCollection
                var fusionDirectorCollections = exsitAppliance.GetRelatedMonitoringObjects(this.FusionDirectorCollectionClass);
                if (fusionDirectorCollections.Any())
                {
                    var exsit = fusionDirectorCollections.First();
                    this.UpdateFusionDirectorCollection(model.FusionDirectorCollection, exsit);
                    discoveryData.Add(exsit);
                }
                else
                {
                    var fusionDirectorCollection = this.CreateFusionDirectorCollection(model.FusionDirectorCollection);
                    discoveryData.Add(fusionDirectorCollection);
                }
                #endregion

                discoveryData.Overwrite(this.MontioringConnector);
                HWLogger.Service.Info($"UpdateAppliance finish.");
            }
            catch (Exception e)
            {
                HWLogger.Service.Error(e, $"Update Appliance Error. [isPolling:{isPolling}]");
            }
        }
Ejemplo n.º 23
0
        protected override void ProcessRecord()
        {
            try
            {
                ManagementPackClass clsIncident = SMHelpers.GetManagementPackClass(ClassTypes.System_WorkItem_Incident, SMHelpers.GetManagementPack(ManagementPacks.System_WorkItem_Incident_Library, _mg), _mg);

                EnterpriseManagementObjectProjection incidentProjection = new EnterpriseManagementObjectProjection(_mg, clsIncident);

                WriteVerbose("Setting basic properties");
                incidentProjection.Object[clsIncident, "Id"].Value = incidentPrefix;

                incidentProjection.Object[clsIncident, "Title"].Value = this.Title;

                if (CreatedDate != null)
                {
                    incidentProjection.Object[clsIncident, "CreatedDate"].Value = this.CreatedDate;
                }

                SMHelpers.UpdateIncident(_mg, clsIncident, incidentProjection,
                                         this.Impact, this.Urgency, this.Status, this.Classification, this.Source, this.SupportGroup, null, null, this.Description, null);


                if (AffectedCIs != null)
                {
                    WriteVerbose("Adding affected CIs");
                    foreach (var item in AffectedCIs)
                    {
                        WriteVerbose(string.Format("Adding {0} as affected configuration item.", item.Object.DisplayName));
                        SMHelpers.AddAffectedCI(incidentProjection, item.Object, _mg);
                    }
                }

                if (AffectedUser != null)
                {
                    WriteVerbose(string.Format("Adding {0} as affected configuration item.", AffectedUser));
                    SMHelpers.AddAffectedUser(incidentProjection, this.AffectedUser, _mg);
                }

                // a bulk operation
                // do in batches of toCommit (set above)
                if (Bulk)
                {
                    toCommit++;
                    idd.Add(incidentProjection);
                    if (toCommit >= batchSize)
                    {
                        idd.Commit(_mg);
                        idd      = new IncrementalDiscoveryData();
                        toCommit = 0;
                    }
                }
                else
                {
                    incidentProjection.Commit();
                }

                if (PassThru)
                {
                    //Pass the new object to the pipeline
                    WriteObject(incidentProjection);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "NewIncident", ErrorCategory.InvalidOperation, Title));
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Create Relationships
        /// </summary>
        private static void CreateRelationships()
        {
            foreach (SyncFailoverGroup sfog in SyncFailoverGroupList)
            {
                // Get SyncFailover Group Object
                EnterpriseManagementObject syncFailoverGroupObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(sfog.SCOM_Object.Id, ObjectQueryOptions.Default);

                // Add Device Relationship
                foreach (f5Device dev in sfog.DeviceList)
                {
                    // Create SyncFailoverGroup->Device Containment Relationship Object
                    ManagementPackRelationship mpr_SyncFailoverGroupContainsDevice = SCOM.GetManagementPackRelationship("AP.F5.LTM.SyncFailoverGroupContainsDevices");
                    CreatableEnterpriseManagementRelationshipObject obj_SyncFailoverGroupContainsDevice = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_SyncFailoverGroupContainsDevice);
                    obj_SyncFailoverGroupContainsDevice.SetSource(syncFailoverGroupObject);
                    obj_SyncFailoverGroupContainsDevice.SetTarget(dev.SCOM_DeviceObject);
                    relationshipData.Add(obj_SyncFailoverGroupContainsDevice);
                }

                // Loop Through Traffic Groups
                foreach (TrafficGroup tg in sfog.TrafficGroupList)
                {
                    // Add Device Relationship
                    foreach (f5Device dev in tg.DeviceGroup.DeviceList)
                    {
                        // Create TrafficGroup->Device Containment Relationship Object
                        ManagementPackRelationship mpr_TrafficGroupContainsDevices = SCOM.GetManagementPackRelationship("AP.F5.LTM.TrafficGroupContainsDevices");
                        CreatableEnterpriseManagementRelationshipObject obj_TrafficGroupContainsDevice = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_TrafficGroupContainsDevices);
                        obj_TrafficGroupContainsDevice.SetSource(tg.SCOM_Object);
                        obj_TrafficGroupContainsDevice.SetTarget(dev.SCOM_DeviceObject);
                        relationshipData.Add(obj_TrafficGroupContainsDevice);
                    }
                }


                // Loop Through Partitions
                foreach (Partition p in sfog.PartitionList)
                {
                    // Create ClientSslProfile -> Certificate Containment
                    foreach (ProfileClientSSL profile in p.ClientSslProfileList)
                    {
                        if (profile.CertificateList.Count > 0)
                        {
                            // Get Client SSL Object
                            EnterpriseManagementObject profile_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);

                            foreach (Certificate cert in profile.CertificateList)
                            {
                                // Get Certificate Object
                                EnterpriseManagementObject cert_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(cert.SCOM_Object.Id, ObjectQueryOptions.Default);

                                // Create Relationship
                                ManagementPackRelationship mpr_Containment = SCOM.GetManagementPackRelationship("AP.F5.LTM.ProfileClientSSL.ContainsCertificates");
                                CreatableEnterpriseManagementRelationshipObject obj_Containment = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_Containment);
                                obj_Containment.SetSource(profile_Object);
                                obj_Containment.SetTarget(cert_Object);
                                relationshipData.Add(obj_Containment);
                            }
                        }
                    }

                    // Create ServerSslProfile -> Certificate Containment
                    foreach (ProfileServerSSL profile in p.ServerSslProfileList)
                    {
                        if (profile.CertificateList.Count > 0)
                        {
                            // Get Client SSL Object
                            EnterpriseManagementObject profile_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);

                            foreach (Certificate cert in profile.CertificateList)
                            {
                                // Get Certificate Object
                                EnterpriseManagementObject cert_Object = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(cert.SCOM_Object.Id, ObjectQueryOptions.Default);

                                // Create Relationship
                                ManagementPackRelationship mpr_Containment = SCOM.GetManagementPackRelationship("AP.F5.LTM.ProfileServerSSL.ContainsCertificates");
                                CreatableEnterpriseManagementRelationshipObject obj_Containment = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_Containment);
                                obj_Containment.SetSource(profile_Object);
                                obj_Containment.SetTarget(cert_Object);
                                relationshipData.Add(obj_Containment);
                            }
                        }
                    }

                    // Add Virtual Server Containments
                    foreach (VirtualServer vs in p.VirtualServerList)
                    {
                        // Get Traffic Group Object
                        EnterpriseManagementObject vipObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(vs.SCOM_Object.Id, ObjectQueryOptions.Default);

                        // Do Client SSL Profiles
                        foreach (ProfileClientSSL profile in vs.ProfileClientSslList)
                        {
                            // Get Profile Object
                            EnterpriseManagementObject profileObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->ProfileClientSSL Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsProfile = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsProfileClientSSL");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsProfile = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsProfile);
                            obj_VirtualServerContainsProfile.SetSource(vipObject);
                            obj_VirtualServerContainsProfile.SetTarget(profileObject);
                            relationshipData.Add(obj_VirtualServerContainsProfile);
                        }
                        // Do Server SSL Profiles
                        foreach (ProfileServerSSL profile in vs.ProfileServerSslList)
                        {
                            // Get Profile Object
                            EnterpriseManagementObject profileObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(profile.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->ProfileServerSSL Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsProfile = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsProfileServerSSL");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsProfile = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsProfile);
                            obj_VirtualServerContainsProfile.SetSource(vipObject);
                            obj_VirtualServerContainsProfile.SetTarget(profileObject);
                            relationshipData.Add(obj_VirtualServerContainsProfile);
                        }


                        // Do Pools
                        if (vs.DefaultPool != null)
                        {
                            // Get Pool Object
                            EnterpriseManagementObject poolObject = SCOM.m_managementGroup.EntityObjects.GetObject <EnterpriseManagementObject>(vs.DefaultPool.SCOM_Object.Id, ObjectQueryOptions.Default);
                            // Create VirtualServer->Pool Containment Relationship Object
                            ManagementPackRelationship mpr_VirtualServerContainsPools = SCOM.GetManagementPackRelationship("AP.F5.LTM.VirtualServerContainsPools");
                            CreatableEnterpriseManagementRelationshipObject obj_VirtualServerContainsPools = new CreatableEnterpriseManagementRelationshipObject(SCOM.m_managementGroup, mpr_VirtualServerContainsPools);
                            obj_VirtualServerContainsPools.SetSource(vipObject);
                            obj_VirtualServerContainsPools.SetTarget(poolObject);
                            relationshipData.Add(obj_VirtualServerContainsPools);
                        }
                    }
                }
            }
        }
        protected virtual IncrementalDiscoveryData PrepareSCOMDiscoveryData(SCOMDiscoveryType direction, IList <T> objects)
        {
            IncrementalDiscoveryData result = new IncrementalDiscoveryData();
            // create object for both incremental and full discovery
            bool hasData = false;

            foreach (T newObject in objects)
            {
                if (!HasAllRequiredProperties(newObject))
                {
                    continue;
                }
                hasData = true;
                CreatableEnterpriseManagementObject             newSeedInstance = new CreatableEnterpriseManagementObject(myMG, mySeedClass);
                CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;
                foreach (var classProperty in mySeedClass.PropertyCollection)
                {
                    try
                    {
                        newSeedInstance[classProperty].Value = newObject[classProperty.Id];
                    }
                    catch (KeyNotFoundException) // ignore situations, when non-key or non-required fields are not available
                    {
                        if (classProperty.Required || classProperty.Key)
                        {
                            throw;
                        }
                    }
                }
                // also try to set DisplayName if available
                try
                {
                    newSeedInstance[SystemId.EntityClassProperties.DisplayNamePropertyId].Value = newObject.GetClassInstanceProperty(SystemId.EntityClassProperties.DisplayNamePropertyId);
                }
                catch (KeyNotFoundException) { } // ignore

                // Unhosted, with specific action point
                if (!mySeedClass.Hosted && myActionPointClass != null && newObject.ActionPoint != null)
                {
                    if (relMAPShouldManageEntity != null)
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(myMG, relMAPShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(newObject.ActionPoint);
                    }
                    // sometimes when specific Health Service is deleted, relationship may revert to All Management Server Pool
                    if (relHSShouldManageEntiry != null && !newObject.ActionPoint.IsInstanceOf(myMG.EntityTypes.GetClass(SystemCenterId.ManagementServicePoolClassId)))
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(myMG, relHSShouldManageEntiry);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(newObject.ActionPoint);
                    }
                    if (relMAPShouldManageEntity == null && relHSShouldManageEntiry == null)
                    {
                        throw new NotSupportedException("Scenario not supported.");
                    }
                }
                // Hosted, in this case myActionPointClass is the hosing class
                if (mySeedClass.Hosted && myActionPointClass != null && newObject.ActionPoint != null)
                {
                    ManagementPackClass hostClass = myActionPointClass;
                    while (hostClass != null)
                    {
                        foreach (ManagementPackProperty hostProperty in hostClass.PropertyCollection)
                        {
                            if (hostProperty.Key)
                            {
                                newSeedInstance[hostProperty].Value = newObject.ActionPoint[hostProperty].Value;
                            }
                        }
                        hostClass = hostClass.FindHostClass();
                    }
                }
                if (hasData)
                {
                    switch (direction)
                    {
                    case SCOMDiscoveryType.Insert:
                    case SCOMDiscoveryType.Update:
                        result.Add(newSeedInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            result.Add(newSomethingShouldManageInstance);
                        }
                        // don't need Hosted==True check, newSomethingShouldManageInstance will be null for hosted classes
                        if (newSomethingShouldManageInstance != null && direction == SCOMDiscoveryType.Update)
                        {
                            PerformRelationshipCleanup(mySeedClass, newSeedInstance, newObject.ActionPoint);
                        }
                        if (mySeedClass.Hosted)
                        {
                        }
                        break;

                    case SCOMDiscoveryType.Delete:
                        result.Remove(newSeedInstance);
                        if (newSomethingShouldManageInstance != null)
                        {
                            result.Remove(newSomethingShouldManageInstance);
                        }
                        break;
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// The insert detials.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public void InsertDetials(RackServer model)
        {
            var discoveryData = new IncrementalDiscoveryData();
            var baseComputer  = this.GetComputerByDeviceId(model.DeviceId);

            // 存在则更新
            if (baseComputer != null)
            {
                this.UpdateRack(model);
                return;
            }
            else
            {
                var newBaseComputer = this.CreateComputer(model.DeviceId);
                discoveryData.Add(newBaseComputer);
            }

            var rackServer = this.CreateRackServer(model);

            rackServer[this.ComputerKey].Value = model.DeviceId;
            discoveryData.Add(rackServer);

            #region Fan

            var fanGroup = this.CreateLogicalGroup(this.FanGroupClass, model.DeviceId);
            discoveryData.Add(fanGroup);
            model.FanList.ForEach(
                x =>
            {
                var fan = this.CreateFan(x);
                fan[this.PartGroupKey].Value = fanGroup[this.PartGroupKey].Value;

                fan[this.HuaweiServerKey].Value = model.DeviceId;
                fan[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(fan);
            });

            #endregion

            #region PSU

            var powerSupplyGroup = this.CreateLogicalGroup(this.PowerSupplyGroupClass, model.DeviceId);
            discoveryData.Add(powerSupplyGroup);
            model.PowerSupplyList.ForEach(
                x =>
            {
                var powerSupply = this.CreatePowerSupply(x);
                powerSupply[this.PartGroupKey].Value    = powerSupplyGroup[this.PartGroupKey].Value;
                powerSupply[this.HuaweiServerKey].Value = model.DeviceId;
                powerSupply[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(powerSupply);
            });

            #endregion

            #region Raid

            var raidGroup = this.CreateLogicalGroup(this.RaidGroupClass, model.DeviceId);
            discoveryData.Add(raidGroup);
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.CreateRaidControl(y);
                raid[this.PartGroupKey].Value    = raidGroup[this.PartGroupKey].Value;
                raid[this.HuaweiServerKey].Value = model.DeviceId;
                raid[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(raid);
            });

            #endregion

            #region CPU

            var cpuGroup = this.CreateLogicalGroup(this.CpuGroupClass, model.DeviceId);
            discoveryData.Add(cpuGroup);
            model.CPUList.ForEach(
                x =>
            {
                var cpu = this.CreateCpu(x);
                cpu[this.PartGroupKey].Value    = cpuGroup[this.PartGroupKey].Value;
                cpu[this.HuaweiServerKey].Value = model.DeviceId;
                cpu[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(cpu);
            });

            #endregion

            #region Memory

            var memoryGroup = this.CreateLogicalGroup(this.MemoryGroupClass, model.DeviceId);
            discoveryData.Add(memoryGroup);
            model.MemoryList.ForEach(
                x =>
            {
                var memory = this.CreateMemory(x);
                memory[this.PartGroupKey].Value    = memoryGroup[this.PartGroupKey].Value;
                memory[this.HuaweiServerKey].Value = model.DeviceId;
                memory[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(memory);
            });

            #endregion

            #region Disk

            var diskGroup = this.CreateLogicalGroup(this.PhysicalDiskGroupClass, model.DeviceId);
            discoveryData.Add(diskGroup);
            model.DiskList.ForEach(
                x =>
            {
                var disk = this.CreateDisk(x);
                disk[this.PartGroupKey].Value    = diskGroup[this.PartGroupKey].Value;
                disk[this.HuaweiServerKey].Value = model.DeviceId;
                disk[this.ComputerKey].Value     = model.DeviceId;
                discoveryData.Add(disk);
            });

            #endregion

            if (!this.ExsitsRackServer(model.DeviceId))
            {
                discoveryData.Commit(this.MontioringConnector);
            }
            else
            {
                discoveryData.Overwrite(this.MontioringConnector);
            }
        }
Ejemplo n.º 27
0
        protected virtual IncrementalDiscoveryData PrepareScomDiscoveryData(ScomDiscoveryType direction, IEnumerable <T> objects)
        {
            // create object for both incremental and full discovery
            var result = new IncrementalDiscoveryData();

            foreach (var @object in objects)
            {
                if ([email protected](_seedClass, _actionPointClass).IsValid)
                {
                    throw new Exception($"Instance has invalid properties or missing required properties");
                }

                var newSeedInstance = new CreatableEnterpriseManagementObject(_managementGroup, _seedClass);
                CreatableEnterpriseManagementRelationshipObject newSomethingShouldManageInstance = null;

                foreach (var classProperty in _seedClass.PropertyCollection)
                {
                    try
                    {
                        newSeedInstance[classProperty].Value = @object[classProperty.Id];
                    }
                    catch (KeyNotFoundException) // ignore situations, when non-key or non-required fields are not available
                    {
                        if (classProperty.Required || classProperty.Key)
                        {
                            throw;
                        }
                    }
                }

                // Set displayname
                try
                {
                    newSeedInstance[_displayNamePropertyId].Value = @object[_displayNamePropertyId];
                }
                catch (Exception ex)
                {
                }

                //Unhosted, with specific action point
                if (!_seedClass.Hosted && _actionPointClass != null && @object.ActionPoint != null)
                {
                    if (_relMapShouldManageEntity != null)
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(_managementGroup, _relMapShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(@object.ActionPoint);
                    }

                    // sometimes when specific Health Service is deleted, relationship may revert to All Management Server Pool
                    if (_relHsShouldManageEntity != null && [email protected](_managementGroup.EntityTypes.GetClass(_managementServicePoolClassId)))
                    {
                        newSomethingShouldManageInstance = new CreatableEnterpriseManagementRelationshipObject(_managementGroup, _relHsShouldManageEntity);
                        newSomethingShouldManageInstance.SetTarget(newSeedInstance);
                        newSomethingShouldManageInstance.SetSource(@object.ActionPoint);
                    }
                    if (_relMapShouldManageEntity == null && _relHsShouldManageEntity == null)
                    {
                        throw new NotSupportedException("Scenario not supported.");
                    }
                }
                // Hosted, in this case myActionPointClass is the hosing class
                if (_seedClass.Hosted && _actionPointClass != null && @object.ActionPoint != null)
                {
                    //Doesn't break reference most likely, needs to be tested
                    var hostClass = _actionPointClass;

                    while (hostClass != null)
                    {
                        foreach (var hostProperty in hostClass.PropertyCollection)
                        {
                            if (hostProperty.Key)
                            {
                                newSeedInstance[hostProperty].Value = @object.ActionPoint[hostProperty].Value;
                            }
                        }

                        hostClass = hostClass.FindHostClass();
                    }
                }

                switch (direction)
                {
                case ScomDiscoveryType.Insert:
                case ScomDiscoveryType.Update:
                    result.Add(newSeedInstance);
                    if (newSomethingShouldManageInstance != null)
                    {
                        result.Add(newSomethingShouldManageInstance);
                    }
                    // don't need Hosted==True check, newSomethingShouldManageInstance will be null for hosted classes
                    if (newSomethingShouldManageInstance != null && direction == ScomDiscoveryType.Update)
                    {
                        PerformRelationshipCleanup(_seedClass, newSeedInstance, @object.ActionPoint);
                    }
                    //if (mySeedClass.Hosted) { }
                    break;

                case ScomDiscoveryType.Delete:
                    result.Remove(newSeedInstance);
                    if (newSomethingShouldManageInstance != null)
                    {
                        result.Remove(newSomethingShouldManageInstance);
                    }
                    break;

                default:
                    throw new Exception("Unknown direction, unable to prepare discovery");
                }
            }

            return(result);
        }
        /// <summary>
        /// The update kun lun.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <exception cref="Exception">Can not find the server</exception>
        public void UpdateKunLun(KunLunServer model)
        {
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateKunLun");
            var oldServer = this.GetKunLunServer(model.DN);

            if (oldServer == null)
            {
                throw new Exception($"Can not find the server:{model.DN}");
            }
            var propertys     = this.KunLunClass.PropertyCollection; // 获取到class的属性
            var discoveryData = new IncrementalDiscoveryData();

            oldServer[this.DisplayNameField].Value     = model.Name;
            oldServer[propertys["Status"]].Value       = model.Status;
            oldServer[propertys["Vendor"]].Value       = "HUAWEI";
            oldServer[propertys["Manufacturer"]].Value = model.Manufacturer;
            oldServer[propertys["UUID"]].Value         = model.UUID;
            oldServer[propertys["IPAddress"]].Value    = model.IpAddress;

            // oldBlade[propertys["iBMCVersion"]].Value = model.Version;
            oldServer[propertys["CPLDVersion"]].Value    = string.Empty;
            oldServer[propertys["UbootVersion"]].Value   = string.Empty;
            oldServer[propertys["ProductSn"]].Value      = model.ProductSN;
            oldServer[propertys["MemoryCapacity"]].Value = model.MemoryCapacity;
            oldServer[propertys["CPUNums"]].Value        = model.CPUNums;
            oldServer[propertys["CPUCores"]].Value       = model.CPUCores;

            // oldBlade[propertys["ServerName"]].Value = model.ServerName;
            oldServer[propertys["BMCMacAddr"]].Value = model.BmcMacAddr;
            oldServer[propertys["eSight"]].Value     = model.ESight;
            discoveryData.Add(oldServer);

            var fanGroup = oldServer.GetRelatedMonitoringObjects(this.FanGroupClass).First();

            discoveryData.Add(fanGroup);

            var relatedFanObjects = fanGroup.GetRelatedMonitoringObjects(this.FanClass);
            var deleteFan         = relatedFanObjects.Where(
                x => model.FanList.All(y => y.UUID != x[this.FanClass.PropertyCollection["UUID"]].Value.ToString()))
                                    .ToList();

            deleteFan.ForEach(x => { discoveryData.Remove(x); });

            model.FanList.ForEach(
                x =>
            {
                var fan = this.UpdateFan(x);
                if (fan == null)
                {
                    var newFan = this.CreateFan(x);
                    newFan[this.ComputerKey].Value     = model.DN;
                    newFan[this.HuaweiServerKey].Value = model.DN;
                    newFan[this.PartGroupKey].Value    = fanGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newFan);
                }
                else
                {
                    discoveryData.Add(fan);
                }
            });

            #region PSU

            var psuGroup = oldServer.GetRelatedMonitoringObjects(this.PowerSupplyGroupClass).First();
            discoveryData.Add(psuGroup);

            var relatedPsuObjects = psuGroup.GetRelatedMonitoringObjects(this.PowerSupplyClass);
            var deletePsu         = relatedPsuObjects.Where(
                x => model.PowerSupplyList.All(
                    y => y.UUID != x[this.PowerSupplyClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deletePsu.ForEach(x => { discoveryData.Remove(x); });
            model.PowerSupplyList.ForEach(
                x =>
            {
                var psu = this.UpdatePowerSupply(x);
                if (psu == null)
                {
                    var newpsu = this.CreatePowerSupply(x);
                    newpsu[this.ComputerKey].Value     = model.DN;
                    newpsu[this.HuaweiServerKey].Value = model.DN;
                    newpsu[this.PartGroupKey].Value    = psuGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newpsu);
                }
                else
                {
                    discoveryData.Add(psu);
                }
            });

            #endregion

            #region Disk

            var diskGroup = oldServer.GetRelatedMonitoringObjects(this.PhysicalDiskGroupClass).First();
            discoveryData.Add(diskGroup);

            var relatedDiskObjects = diskGroup.GetRelatedMonitoringObjects(this.PhysicalDiskClass);
            var deleteDisk         = relatedDiskObjects.Where(
                x => model.DiskList.All(
                    y => y.UUID != x[this.PhysicalDiskClass.PropertyCollection["UUID"]].Value.ToString())).ToList();
            deleteDisk.ForEach(x => { discoveryData.Remove(x); });
            model.DiskList.ForEach(
                y =>
            {
                var disk = this.UpdateDisk(y);
                if (disk == null)
                {
                    var newDisk = this.CreateDisk(y);
                    newDisk[this.ComputerKey].Value     = model.DN;
                    newDisk[this.HuaweiServerKey].Value = model.DN;
                    newDisk[this.PartGroupKey].Value    = diskGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newDisk);
                }
                else
                {
                    discoveryData.Add(disk);
                }
            });

            #endregion

            #region Raid

            var raidGroup = oldServer.GetRelatedMonitoringObjects(this.RaidGroupClass).First();
            discoveryData.Add(raidGroup);

            var relatedRaidObjects = raidGroup.GetRelatedMonitoringObjects(this.RaidClass);
            var deleteRaid         = relatedRaidObjects.Where(
                x => model.RaidList.All(
                    y => y.UUID != x[this.RaidClass.PropertyCollection["UUID"]].Value.ToString()))
                                     .ToList();
            deleteRaid.ForEach(x => { discoveryData.Remove(x); });
            model.RaidList.ForEach(
                y =>
            {
                var raid = this.UpdateRaidControl(y);
                if (raid == null)
                {
                    var newRaid = this.CreateRaidControl(y);
                    newRaid[this.ComputerKey].Value     = model.DN;
                    newRaid[this.HuaweiServerKey].Value = model.DN;
                    newRaid[this.PartGroupKey].Value    = raidGroup[this.PartGroupKey].Value;
                    discoveryData.Add(newRaid);
                }
                else
                {
                    discoveryData.Add(raid);
                }
            });

            #endregion

            discoveryData.Overwrite(this.MontioringConnector);
            HWLogger.NOTIFICATION_PROCESS.Debug("Start UpdateKunLun");
        }
Ejemplo n.º 29
0
        void buildActivitiesList(IList <EnterpriseManagementObject> activitiesList, EnterpriseManagementObject emoReleaseRecord, EnterpriseManagementObject emoProject, PublishedProject project)
        {
            int sequenceId = getStartingSequenceId(activitiesList, project);

            var lstEndingActivities = activitiesList.Where(
                a => (int)a[null, "SequenceId"].Value >= sequenceId && !a.IsInstanceOf(mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.Project"))).ToList();

            foreach (PublishedTask task in project.Tasks)
            {
                try
                {
                    if (activitiesList.Any(t => t[null, "TaskGUID"] != null && (Guid)t[null, "TaskGUID"].Value == task.Id))
                    {
                        //activity exists.  Get its current sequence ID and move up from there.
                        var emoTaskActivity = activitiesList.First(t => t[null, "TaskGUID"] != null && (Guid)t[null, "TaskGUID"].Value == task.Id);

                        if (string.IsNullOrEmpty((string)emoProjectAutomationSettings[null, "TaskInsertionTag"].Value))
                        {
                            iddBucket.Add(buildTaskActivity(task, emoReleaseRecord, emoTaskActivity, emoProject, ref sequenceId));
                            lstEndingActivities.Remove(emoTaskActivity);
                        }

                        else
                        {
                            if (task.Name.Contains((string)emoProjectAutomationSettings[null, "TaskInsertionTag"].Value))
                            {
                                iddBucket.Add(buildTaskActivity(task, emoReleaseRecord, emoTaskActivity, emoProject, ref sequenceId));
                                lstEndingActivities.Remove(emoTaskActivity);
                            }
                            // otherwise do nothing with this task.
                        }
                    }
                    else
                    {
                        CreatableEnterpriseManagementObject cemoProjectTaskActivity = new CreatableEnterpriseManagementObject(emg,
                                                                                                                              mpcClasses.First(mpc => mpc.Name == "Cireson.ProjectAutomation.ProjectTask.Activity"));

                        if (string.IsNullOrEmpty((string)emoProjectAutomationSettings[null, "TaskInsertionTag"].Value))
                        {
                            iddBucket.Add(buildTaskActivity(task, emoReleaseRecord, cemoProjectTaskActivity, emoProject, ref sequenceId));
                        }
                        else
                        if (task.Name.Contains((string)emoProjectAutomationSettings[null, "TaskInsertionTag"].Value))
                        {
                            iddBucket.Add(buildTaskActivity(task, emoReleaseRecord, cemoProjectTaskActivity, emoProject, ref sequenceId));
                        }
                    }
                }
                catch (EnterpriseManagementException ex)
                {
                    exceptionsList.Add(new ProjectTaskImportException(string.Format("An error occured while processing task '{0}'.  Unable to relate the task to '{1}'", task.Name, emoReleaseRecord.DisplayName), ex));
                }

                if (lstEndingActivities != null)
                {
                    foreach (var activity in lstEndingActivities.OrderBy(a => (int)a[null, "SequenceId"].Value))
                    {
                        iddBucket.Add(resequenceActivity(activity, ref sequenceId));
                    }
                }
            }
        }