Example #1
0
 /// <summary>
 /// Gets all update intervals for a specific system in combination with a plugin.
 /// </summary>
 /// <param name="monitoredSystemID">The ID of the system to get the update intervals from.</param>
 /// <param name="pluginName">The plugin to get the update intervals form.</param>
 /// <returns>A list containing tuples of IndicatorName | UpdateInterval.</returns>
 public List <Tuple <string, TimeSpan> > GetUpdateIntervals(int monitoredSystemID, string pluginName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         return(GetUpdateIntervalsByMonitoredSystemIDAndPluginName(dataContext, monitoredSystemID, PrecompiledQueries.GetPluginMetadataIDByName(dataContext, pluginName)).ToList());
     }
 }
Example #2
0
        /// <summary>
        /// Initializes the clusters with the credentials stored in the database.
        /// </summary>
        private void InitializeClusters()
        {
            try
            {
                var credentials = from p in DataContextFactory.CreateReadOnlyDataContext().ClusterCredential
                                  select p;

                var threads = new List <Thread>();

                foreach (var current in credentials)
                {
                    try
                    {
                        var clusterman = new ClusterManager();

                        var thread = new Thread(new ParameterizedThreadStart(clusterman.Initialize));

                        threads.Add(thread);
                        thread.Start(current);
                    }
                    catch (Exception e)
                    {
                        threads.ElementAt(threads.Count - 1).Abort();
                        MISD.Core.Logger.Instance.WriteEntry("Bootstrapper_InitializeClusters: Problem initializing custer with headnode " + current.HeadNodeUrl + ", " + e.StackTrace, LogType.Exception);
                    }
                }

                threads.ForEach(p => p.Join());
            }
            catch (Exception e)
            {
                MISD.Core.Logger.Instance.WriteEntry("Bootstrapper_InitializeClusters: Problem initializing clusters, " + e.StackTrace, LogType.Exception);
            }
        }
Example #3
0
        public int AddOU(string name, int?fatherOU, DateTime updateTime)
        {
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                try
                {
                    if (fatherOU != null)
                    {
                        var existParent = (from p in dataContext.OrganizationalUnit
                                           let parent = p.ID == fatherOU
                                                        where parent
                                                        select p).First();

                        //create OU
                        return(this.CreateOU(name, existParent.FQDN, updateTime));
                    }
                    else
                    {
                        //create OU
                        return(this.CreateOU(name, null, updateTime));
                    }
                }
                catch (Exception e)
                {
                    //logging exception
                    var messageEx1 = new StringBuilder();
                    messageEx1.Append("ClientWebService_AddOU: ");
                    messageEx1.Append("Adding of OU" + name + " failed. " + e.ToString());
                    MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception);
                    return(-1);
                }
            }
        }
        /// <summary>
        /// Gets the metric for a specific monitored system and an indicator.
        /// </summary>
        /// <param name="monitoredSystemID">The ID of the system that belongs to the metric.</param>
        /// <param name="pluginName">The plugins for the metric.</param>
        /// <param name="indicator">The indicator for the metric.</param>
        /// <returns>A tuple containing the expressions (for warning and critical) of the metric.</returns>
        public void GetMetric(int monitoredSystemID, string pluginName, string indicator, out string statementWarning, out string statementCritical)
        {
            try
            {
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    string key = monitoredSystemID.ToString() + "." + pluginName + "." + indicator;
                    Tuple <string, string> result = cacheMan.Get(key) as Tuple <string, string>;

                    if (result == null)
                    {
                        result = GetFilterStatements(dataContext, monitoredSystemID, pluginName, indicator);
                    }

                    statementWarning  = result.Item1;
                    statementCritical = result.Item2;
                }
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("MetricManager_GetMetric: Problem getting metric for system " + monitoredSystemID + " and plugin " + pluginName + " and indicator " + indicator + ", returning null. " + e.ToString(), LogType.Exception);
                statementWarning  = null;
                statementCritical = null;
            }
        }
Example #5
0
        /// <summary>
        /// Gets the complete data for serveral plugins of certain workstations.
        /// This method can be used to retrieve Level 2 data .
        /// </summary>
        /// <param name="macAndPluginName"> A list containing tuples of:  MAC | PluginName</param>
        /// <returns>A list containing tuples of: MAC | PluginName | IndicatorName | Value | Mapping | Time</returns>
        public List <Tuple <string, string, string, string, MappingState, DateTime> > GetPluginData(List <Tuple <string, string> > macAndPluginName, int?numberOfIndicators)
        {
            List <Tuple <string, string, string, DateTime?, DateTime?, int?> > macAndProperties = new List <Tuple <string, string, string, DateTime?, DateTime?, int?> >();

            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                foreach (var names in macAndPluginName)
                {
                    try
                    {
                        var indicators = (from p in dataContext.Indicator
                                          where p.MonitoredSystem.MacAddress == names.Item1
                                          where p.PluginMetadata.Name == names.Item2
                                          select p.Name).ToList();
                        foreach (var ind in indicators)
                        {
                            macAndProperties.Add(new Tuple <string, string, string, DateTime?, DateTime?, int?>(names.Item1, names.Item2, ind, null, null, numberOfIndicators));
                        }
                    }
                    catch (Exception e)
                    {
                        //logging exception
                        #region logging
                        var messageEx = new StringBuilder();
                        messageEx.Append("ValueManager_GetPluginData: Can't create List of PluginDatas" + ". " + e.ToString() + "| " + e.StackTrace);
                        MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);
                        #endregion
                    }
                }

                //get data
                return(GetDataOLDAPPROACH(macAndProperties));
            }
        }
Example #6
0
        /// <summary>
        /// Gets an update interval for a specific system in combination with a plugin and an indicator.
        /// </summary>
        /// <param name="monitoredSystemID">The ID of the system to get the update interval from.</param>
        /// <param name="pluginName">The plugin to get the update intervals from.</param>
        /// <param name="indicatorName">The indicator to get the update interval from.</param>
        /// <returns>A long containing the update interval.</returns>
        public long GetUpdateInterval(int monitoredSystemID, string pluginName, string indicatorName)
        {
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                try
                {
                    var result = GetUpdateIntervalFunc(dataContext, monitoredSystemID, pluginName, indicatorName);
                    if (result <= 0)
                    {
                        result = long.MaxValue;
                    }
                    return(result);
                }
                catch (Exception e)
                {
                    //logging exception
                    var messageEx1 = new StringBuilder();
                    messageEx1.Append("WorkstationWebService_GetUpdateInterval: ");
                    messageEx1.Append("Problems getting update intervals fo " + monitoredSystemID + " and " + pluginName + " and " + indicatorName + ", returing long.MaxValue. " + e.ToString());
                    MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Warning);

                    return(long.MaxValue);
                }
            }
        }
Example #7
0
 /// <summary>
 /// Gets all filters for a certain plugin of a given workstation.
 /// </summary>
 /// <param name="monitoredSystemID">The ID of the monitored system.</param>
 /// <param name="pluginName">The name of the plugin.</param>
 /// <returns>A list containing tuples of: IndicatorName | FilterStatement.</returns>
 public List <Tuple <string, string> > GetFilters(int monitoredSystemID, string pluginName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         return(GetFiltersForMonitoredSystem(dataContext, monitoredSystemID, pluginName).ToList());
     }
 }
Example #8
0
 public bool UploadIndicatorValues(string monitoredSystemMAC, string pluginName, List <Tuple <string, Object, MISD.Core.DataType, DateTime> > indicatorValues)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         return(MISD.Server.Manager.WorkstationManager.Instance.UploadIndicatorValues(monitoredSystemID, pluginName, indicatorValues));
     }
 }
Example #9
0
 public List <Core.PluginMetadata> GetPluginList(string monitoredSystemMAC)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         return(MISD.Server.Manager.PluginManager.Instance.GetPluginList(monitoredSystemID));
     }
 }
Example #10
0
 public long GetUpdateInterval(string monitoredSystemMAC, string pluginName, string indicatorName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         return(MISD.Server.Manager.UpdateIntervalManager.Instance.GetUpdateInterval(monitoredSystemID, pluginName, indicatorName));
     }
 }
Example #11
0
 public List <Tuple <string, string> > GetFilters(string monitoredSystemMAC, string pluginName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         return(MISD.Server.Manager.FilterManager.Instance.GetFilters(monitoredSystemID, pluginName));
     }
 }
Example #12
0
 public string GetFilter(string monitoredSystemMAC, string pluginName, string indicatorName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         return(FilterManager.Instance.GetFilter(monitoredSystemID, pluginName, indicatorName));
     }
 }
Example #13
0
 /// <summary>
 /// Initializes the cleaner job scheduler.
 /// </summary>
 protected override void Initialize()
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         // Create the cleaner jobs.
         this.Jobs.Add(new CleanerJob());
         this.Start();
     }
 }
Example #14
0
 public List <Core.PluginFile> DownloadPlugins(string monitoredSystemMAC, List <string> pluginNames)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int  monitoredSystemID       = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         byte monitoredSystemPlatform = PrecompiledQueries.GetMonitoredSystemPlatformByID(dataContext, monitoredSystemID);
         return(MISD.Server.Manager.PluginManager.Instance.DownloadPlugins((Core.Platform)monitoredSystemPlatform, pluginNames));
     }
 }
Example #15
0
        /// <summary>
        /// Sends all e-mail-warnings.
        /// </summary>
        /// <param name="monitoredSystemID">The ID of the system that caused the warning.</param>
        /// <param name="criticalValueReceived">The time when the critical value was received.</param>
        /// <param name="pluginName">The plugin that aquired the value.</param>
        /// <param name="indicator">The indicator of the value.</param>
        /// <param name="criticalValue">The value that is mapped to critical.</param>
        public void SendAllWarnings(int monitoredSystemID, DateTime criticalValueReceived,
                                    string pluginName, string indicator, string criticalValue)
        {
            try
            {
                List <MailAddress> list;
                if (warningMails.ContainsKey(monitoredSystemID))
                {
                    warningMails.TryGetValue(monitoredSystemID, out list);
                }
                else
                {
                    using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                    {
                        list = (from observer in dataContext.EmailObserver
                                join mail in dataContext.Email on observer.EmailID equals mail.ID
                                join ws in dataContext.MonitoredSystem on observer.MonitoredSystemID equals ws.ID
                                where ws.ID == monitoredSystemID
                                select new MailAddress(mail.Address, mail.ReceiverName)
                                ).ToList <MailAddress>();
                        warningMails.Add(monitoredSystemID, list);
                    }
                }
                //get mail adresses from the db

                if (list != null)
                {
                    if (list.Count > 0)
                    {
                        //generate text
                        string emailText = this.GenerateWarningMail(monitoredSystemID, criticalValueReceived,
                                                                    pluginName, indicator, criticalValue);

                        //send the mail
                        var from = new MailAddress(Properties.Settings.Default.MailAdressFrom, Properties.Settings.Default.WarningMailFromDisplayName);
                        this.SendMail(from, list, Properties.Settings.Default.WarningMailSubject, emailText);
                    }
                }
                else
                {
                    //logging
                    StringBuilder messageEx1 = new StringBuilder();
                    messageEx1.Append("Mailer_SendAllWarnings: ");
                    messageEx1.Append("Can't send mail for system " + monitoredSystemID + "  .");
                    messageEx1.Append("The list of emails wasn't correctly loaded!");
                    Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception);
                }
            }
            catch (Exception e)
            {
                //logging
                StringBuilder messageEx1 = new StringBuilder();
                messageEx1.Append("Mailer_SendAllWarnings: ");
                messageEx1.Append("Can't send mail for system " + monitoredSystemID + ". " + e.ToString());
                Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Warning);
            }
        }
Example #16
0
 public bool UploadIndicatorValue(string monitoredSystemMAC, string pluginName, string indicatorValueName, object value, DataType valueDataType, DateTime aquiredTimestamp)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         int monitoredSystemID = PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, monitoredSystemMAC);
         //Manager.Logger.Instance.WriteEntry("Reveiving Data from " + monitoredSystemMAC + " via single UploadIndicatorValue", LogType.Info);
         List <Tuple <string, object, DataType, DateTime> > list = new List <Tuple <string, object, DataType, DateTime> >();
         list.Add(new Tuple <string, object, DataType, DateTime>(indicatorValueName, value, valueDataType, aquiredTimestamp));
         return(MISD.Server.Manager.WorkstationManager.Instance.UploadIndicatorValues(monitoredSystemID, pluginName, list));
     }
 }
Example #17
0
 /// <summary>
 /// Gets all update intervals for a certain plugin of a given workstation .
 /// </summary>
 /// <param name ="monitoredSystemID">The ID of the workstation.</param>
 /// <param name ="pluginName">The name of the plugin.</param>
 /// <returns>A list containing tuples of: IndicatorName | Duration.</returns>
 public List <Tuple <string, long?> > GetUpdateIntervalsLong(int monitoredSystemID, string pluginName)
 {
     using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
     {
         var indicators = from p in dataContext.Indicator
                          let monitoredSystem = p.MonitoredSystem.ID == monitoredSystemID
                                                let plugin = p.PluginMetadata.Name == pluginName
                                                             where monitoredSystem && plugin
                                                             select p;
         var intervals = from p in indicators
                         select new Tuple <string, long?>(p.Name, p.UpdateInterval);
         return(intervals.ToList());
     }
 }
Example #18
0
        /// <summary>
        /// Adds a filter to the availableFilters by reloading it from the database and removing it from the available filtes first
        /// </summary>
        /// <param name="monitoredSystemID">The ID of the monitored System.</param>
        /// <param name="pluginName">The name of the Plugin.</param>
        /// <param name="indicator">The indicator name.</param>
        /// <returns>The filterStatement as string (to not have to look it up again).</returns>
        private string AddFilterFromDatabase(int monitoredSystemID, string pluginName, string indicator)
        {
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                var indi = (from p in dataContext.Indicator
                            let a = p.MonitoredSystemID == monitoredSystemID
                                    let b = p.PluginMetadata.Name == pluginName
                                            let c = p.Name == indicator
                                                    where a && b && c
                                                    select p).FirstOrDefault();

                string filter = indi.FilterStatement;
                UpdateFilter(monitoredSystemID, pluginName, indicator, filter);
                return(filter);
            }
        }
Example #19
0
        private Mailer()
        {
            //create directory
            if (Directory.Exists(TemplatePath))
            {
                Directory.CreateDirectory(TemplatePath);
            }

            // load Daily-Mails from database
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                dailyMails = (from mail in dataContext.Email
                              where mail.DailMail == true
                              select new MailAddress(mail.Address, mail.ReceiverName)).ToList <MailAddress>();
            }
        }
Example #20
0
        /// <summary>
        /// Gets the data for all plugins of the given workstations .
        /// This method can be used to retrieve Level 3 data .
        /// </summary>
        /// <param name="mac">A list containing tuples of:  MAC | Maximum numer of results? per inticator</param>
        /// <returns>A list containing tuples of: MAC | PluginName | IndicatorName | Value | Mapping | Time</returns>
        public List <Tuple <string, string, string, string, MappingState, DateTime> > GetCompletePluginData(List <string> macList, int?numberOfIndicators)
        {
            List <Tuple <string, string> > macAndPluginName = new List <Tuple <string, string> >();

            try
            {
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    foreach (var mac in macList)
                    {
                        try
                        {
                            var pluginNames = (from p in dataContext.Indicator
                                               where p.MonitoredSystem.MacAddress == mac
                                               select p.PluginMetadata.Name).Distinct().ToList();

                            foreach (var pName in pluginNames)
                            {
                                macAndPluginName.Add(new Tuple <string, string>(mac, pName));
                            }
                        }
                        catch (Exception e)
                        {
                            #region logging
                            //logging exception
                            var messageEx = new StringBuilder();
                            messageEx.Append("ValueManager_GetCompletePluginData: Can't create List of PluginDatas" + ". " + e.ToString());
                            MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);
                            #endregion
                        }
                    }
                }

                //get data
                return(GetPluginData(macAndPluginName, numberOfIndicators));
            }
            catch (Exception e)
            {
                #region logging
                //logging exception
                var messageEx = new StringBuilder();
                messageEx.Append("ValueManager_GetCompletePluginData: Can't create List of PluginDatas" + ". " + e.ToString());
                MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);
                #endregion
                return(null);
            }
        }
Example #21
0
 /// <summary>
 /// Check if a given organisation unit exist.
 /// </summary>
 /// <param name="fqdn">FQDN of the organisation unit</param>
 /// <returns></returns>
 public bool Exists(string fqdn)
 {
     try
     {
         using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
         {
             return((from p in dataContext.OrganizationalUnit
                     where p.FQDN == fqdn
                     select p).Count() >= 1);
         }
     }
     catch (Exception e)
     {
         Logger.Instance.WriteEntry("OUManager_Exists: FQDN: " + fqdn + " couldnt be aquired! " + e.ToString(), LogType.Warning);
         return(false);
     }
 }
Example #22
0
        /// <summary>
        /// Retuns all observer of an monitored system
        /// </summary>
        /// <param name="userID">ID of the users email adress</param>
        /// <returns>List of MAC adress </returns>
        public List <WorkstationInfo> GetObserver(int userID)
        {
            List <WorkstationInfo> result = new List <WorkstationInfo>();

            try
            {
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    var msIDs = (from q in dataContext.EmailObserver
                                 where q.EmailID == userID
                                 select q.MonitoredSystem.ID).ToList();

                    foreach (var ms in msIDs)
                    {
                        //update mapping state
                        ValueManager.Instance.UpdateMonitoredSystemMappingState(ms);

                        var monitoredSystem = PrecompiledQueries.GetMonitoredSystemByID(dataContext, ms);

                        //create result
                        var workstationinfo = new WorkstationInfo()
                        {
                            Name        = monitoredSystem.Name,
                            ID          = monitoredSystem.ID,
                            FQDN        = monitoredSystem.FQDN,
                            OuID        = monitoredSystem.OrganizationalUnitID,
                            IsAvailable = monitoredSystem.IsAvailable,
                            CurrentOS   = ((MISD.Core.Platform)monitoredSystem.OperatingSystem).ToString(),
                            MacAddress  = monitoredSystem.MacAddress,
                            State       = monitoredSystem.Status.HasValue ? (MappingState)monitoredSystem.Status : MappingState.OK
                        };
                        result.Add(workstationinfo);
                    }
                }

                return(result);
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("Mailer_GetObserver: Can't create result: " + e.StackTrace, LogType.Exception);
                return(null);
            }
        }
Example #23
0
        /// <summary>
        /// Updates the mapping state of a monitored system, if the mapping duration of this monitored system is out of date
        /// </summary>
        /// <param name="monitoredSystemMac">ID of the monitored system to update</param>
        public void UpdateMappingState(int monitoredSystemID)
        {
            try
            {
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    var monitoredSystem = PrecompiledQueries.GetMonitoredSystemByID(dataContext, monitoredSystemID);

                    if (monitoredSystem.MacAddress != null)
                    {
                        UpdateMappingState(monitoredSystem.MacAddress);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("ValueManager_UpdateMappingState: Can't update the mapping of workstation " + monitoredSystemID + ". " + e.StackTrace, LogType.Exception);
            }
        }
Example #24
0
        /// <summary>
        /// Gets all email user datas
        /// </summary>
        /// <returns>List of Tuple with data: ID | username | user mail adress | daily mail </returns>
        public List <Tuple <int, string, string, bool> > GetAllMailData()
        {
            try
            {
                List <Tuple <int, string, string, bool> > result;
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    result = (from q in dataContext.Email
                              select new Tuple <int, string, string, bool>(q.ID, q.ReceiverName, q.Address, q.DailMail)).ToList();
                }

                return(result);
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("Mailer_GetAllMailData: Can't create result: " + e.StackTrace, LogType.Exception);
                return(null);
            }
        }
Example #25
0
        /// <summary>
        /// Loads the HTML-template for the warning mail and generates the mail
        /// Template tags: [%WSName%], [%Date%], [%PluginName%], [%Indicator%], [%Value%]
        /// </summary>
        /// <returns>String containing the HTML-Email-Message</returns>
        private string GenerateWarningMail(int monitoredSystemID, DateTime criticalValueReceived,
                                           string pluginName, string indicator, string criticalValue)
        {
            string template = "";

            //instantiate the WarningMailParser
            parser.ClearTags();

            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                StreamReader reader = null;
                try
                {
                    string name = PrecompiledQueries.GetMonitoredSystemNameByID(dataContext, monitoredSystemID);
                    parser.AddTag("[%WSName%]", name);
                    parser.AddTag("[%Date%]", criticalValueReceived.ToString());
                    parser.AddTag("[%PluginName%]", pluginName);
                    parser.AddTag("[%Indicator%]", indicator);
                    parser.AddTag("[%Value%]", criticalValue);

                    //load the warning mail template
                    reader = new StreamReader(TemplatePath);

                    template = reader.ReadToEnd();
                }
                catch (Exception e)
                {
                    //logging
                    StringBuilder messageEx1 = new StringBuilder();
                    messageEx1.Append("Mailer_GenerateWarningMail: ");
                    messageEx1.Append("Can't load warning mail template. " + e.ToString());
                    Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception);
                }
                finally
                {
                    reader.Close();
                }

                //Parese template string
                return(parser.ParseTemplateString(template));
            }
        }
Example #26
0
        /// <summary>
        /// Gets the IDs of all workstations that are known to the server .
        /// </summary>
        /// <returns>A list of workstation names .</returns>
        public List <string> GetWorkstationMACs()
        {
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                try
                {
                    //gets PluginMetadata and converts into DataHolder.PluginMetadata
                    var workstations = (from p in dataContext.MonitoredSystem
                                        where !p.IsIgnored
                                        select p.MacAddress).ToList();
                    return(workstations);
                }
                catch (Exception e)
                {
                    //logging exception
                    var messageEx = new StringBuilder();
                    messageEx.Append("ValueManager_GetWorkstationMACS: Can't create List of WorkstationNames" + ". " + e.ToString());
                    MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);

                    return(null);
                }
            }
        }
Example #27
0
        private string GenerateDailyMail()
        {
            long now = DateTime.UtcNow.Ticks;

            List <WorkstationInfo> maintanceList = new List <WorkstationInfo>();
            List <WorkstationInfo> criticalList  = new List <WorkstationInfo>();
            List <WorkstationInfo> warningList   = new List <WorkstationInfo>();

            //generate template data
            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                #region get maintance data

                try
                {
                    maintanceList = (from ms in dataContext.MonitoredSystem
                                     join main in dataContext.Maintenance on ms.ID equals main.MonitoredSystemID
                                     let start = main.Beginning != null
                                                 let end = main.End == null
                                                           where start & end
                                                           group ms by ms.ID into msGroup
                                                           select new WorkstationInfo()
                    {
                        ID = msGroup.First().ID,
                        Name = msGroup.First().Name,
                        FQDN = msGroup.First().FQDN,
                        IsAvailable = (bool)msGroup.First().IsAvailable,
                        CurrentOS = ((Platform)msGroup.First().OperatingSystem).ToString(),
                        State = (MappingState)MappingState.Maintenance
                    }).ToList <WorkstationInfo>();
                }
                catch (Exception)
                {
                    Logger.Instance.WriteEntry("Mailer_GenerateDailyMail: Can't load maintance list.", LogType.Warning);
                }

                #endregion

                #region get critical data

                try
                {
                    criticalList = (from ms in dataContext.MonitoredSystem
                                    join ind in dataContext.Indicator on ms.ID equals ind.MonitoredSystemID
                                    join value in dataContext.IndicatorValue on ind.ID equals value.IndicatorID
                                    let mapping = value.Mapping == (byte)MappingState.Critical
                                                  let mappingDuration = (ind.MappingDuration == null) ? 864000000000 : ind.MappingDuration
                                                                        let deadLineTicks = now - mappingDuration
                                                                                            let indicatorValueTicks = value.Timestamp
                                                                                                                      where mapping & (indicatorValueTicks >= deadLineTicks)
                                                                                                                      group ms by ms.ID into msGroup
                                                                                                                      select new WorkstationInfo()
                    {
                        ID = msGroup.First().ID,
                        Name = msGroup.First().Name,
                        FQDN = msGroup.First().FQDN,
                        IsAvailable = (bool)msGroup.First().IsAvailable,
                        CurrentOS = ((Platform)msGroup.First().OperatingSystem).ToString(),
                        State = (MappingState)MappingState.Maintenance
                    }).ToList <WorkstationInfo>();
                }
                catch (Exception)
                {
                    Logger.Instance.WriteEntry("Mailer_GenerateDailyMail: Can't load critical list.", LogType.Warning);
                }

                #endregion

                #region get warning data

                try
                {
                    warningList = (from ms in dataContext.MonitoredSystem
                                   join ind in dataContext.Indicator on ms.ID equals ind.MonitoredSystemID
                                   join value in dataContext.IndicatorValue on ind.ID equals value.IndicatorID
                                   let mapping = value.Mapping == (byte)MappingState.Warning
                                                 let mappingDuration = (ind.MappingDuration == null) ? 864000000000 : ind.MappingDuration
                                                                       let deadLineTicks = now - mappingDuration
                                                                                           let indicatorValueTicks = value.Timestamp
                                                                                                                     where mapping & (indicatorValueTicks >= deadLineTicks)
                                                                                                                     group ms by ms.ID into msGroup
                                                                                                                     select new WorkstationInfo()
                    {
                        ID = msGroup.First().ID,
                        Name = msGroup.First().Name,
                        FQDN = msGroup.First().FQDN,
                        IsAvailable = (bool)msGroup.First().IsAvailable,
                        CurrentOS = ((Platform)msGroup.First().OperatingSystem).ToString(),
                        State = (MappingState)MappingState.Maintenance
                    }).ToList <WorkstationInfo>();
                }
                catch (Exception)
                {
                    Logger.Instance.WriteEntry("Mailer_GenerateDailyMail: Can't load warning list.", LogType.Warning);
                }

                #endregion
            }

            var mailData = new DailyMailTemplateData()
            {
                maintanceWorkstations = (maintanceList == null) ? new List <WorkstationInfo>() : maintanceList,
                criticalWorkstations  = (criticalList == null) ? new List <WorkstationInfo>() : criticalList,
                waringWorkstations    = (warningList == null) ? new List <WorkstationInfo>() : warningList
            };

            //generate email text
            DailyMailTemplate page      = new DailyMailTemplate(mailData);
            string            emailText = page.TransformText();

            return(emailText);
        }
Example #28
0
        /// <summary>
        /// Gets the complete data for serveral plugins of certain workstations and a certain timespan.
        /// </summary>
        /// <param name="macAndProperties"> A list containing tuples of:  MAC | PluginName | IndicatorName | LowerBound? | UpperBound? | Maximum numer of results?</param>
        /// <returns>A list containing tuples of: MAC | PluginName | IndicatorName | Value | Mapping | Time</returns>
        public List <Tuple <string, string, string, string, MappingState, DateTime> > GetData(List <Tuple <string, string, string, DateTime?, DateTime?, int?> > macAndProperties)
        {
            #region check arguments
            if (macAndProperties == null || macAndProperties.Count == 0)
            {
                throw new ArgumentException("macAndProperties list item false.", "macAndProperties");
            }
            #endregion

            List <Tuple <string, string, string, string, MappingState, DateTime> > result = new List <Tuple <string, string, string, string, MappingState, DateTime> >();

            try
            {
                using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    //current:  (MAC | PluginName | IndicatorName | LowerBound? | UpperBound? | Maximum numer of results?)
                    foreach (var c in macAndProperties)
                    {
                        // TODO Arno entfernen
                        break;

                        #region check arguments
                        if (c.Item1 == null || c.Item1 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "macAdress (Item1)");
                        }
                        if (c.Item2 == null || c.Item2 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "pluginName (Item2)");
                        }
                        if (c.Item3 == null || c.Item3 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "IndicatorName (Item3)");
                        }

                        #endregion

                        //update mapping state
                        UpdateMappingState(c.Item1);

                        //set numbers of values
                        int  numbersOfValues = (c.Item6 != null) ? (int)c.Item6 : int.MaxValue;
                        long lowerTicks      = (c.Item4 != null) ? c.Item4.Value.Ticks : 0;
                        long upperTicks      = (c.Item5 != null) ? c.Item5.Value.Ticks : long.MaxValue;

                        //get valueX type
                        var type = (from q in dataContext.Indicator
                                    where q.Name == c.Item3
                                    select(Core.DataType) q.ValueType).First();


                        //get valueX, create sub-results and add them to the result
                        string tableName = "";
                        #region byte
                        if (type == Core.DataType.Byte)
                        {
                            tableName = "ValueByte";
                        }
                        #endregion

                        #region int
                        if (type == DataType.Int)
                        {
                            tableName = "ValueInt";
                        }
                        #endregion

                        #region float
                        if (type == DataType.Float)
                        {
                            tableName = "ValueFloat";
                        }
                        #endregion

                        #region string
                        if (type == DataType.String)
                        {
                            tableName = "ValueString";
                        }
                        #endregion

                        if (tableName != "")
                        {
                            #region query
                            var query = new StringBuilder();
                            query.Append("SELECT TOP {5} A.Timestamp, A.Mapping, V.Value FROM (SELECT ValueID,Timestamp,Mapping FROM MISD.dbo.IndicatorValue IV where IV.Timestamp>={3}  AND IV.Timestamp<={4} AND IV.IndicatorID IN ");
                            query.Append("(SELECT IndicatorID FROM ");
                            query.Append("(Select ID AS IndicatorID,MonitoredSystemID from ( ");
                            query.Append("Select ID AS PM_ID FROM MISD.dbo.PluginMetadata PM ");
                            query.Append("WHERE PM.Name = '{1}' ) PM ");
                            query.Append("JOIN MISD.dbo.Indicator I ON I.PluginMetadataID = PM.PM_ID WHERE I.Name = '{2}') IP ");
                            query.Append("JOIN MISD.dbo.MonitoredSystem MS ON IP.MonitoredSystemID = MS.ID WHERE MS.MacAddress = '{0}' ");
                            query.Append(") ");
                            query.Append(") A JOIN MISD.dbo.{6} V on V.ID = A.ValueID ");
                            query.Append("ORDER BY A.Timestamp");
                            #endregion
                            var tempResult = dataContext.ExecuteQuery <ValueResult>(
                                query.ToString(),
                                c.Item1,
                                c.Item2,
                                c.Item3,
                                lowerTicks,
                                upperTicks,
                                numbersOfValues,
                                tableName).ToList();
                            Logger.Instance.WriteEntry(tempResult.ToString(), LogType.Exception);
                            foreach (ValueResult b in tempResult)
                            {
                                Tuple <string, string, string, string, MappingState, DateTime> t = new Tuple <string, string, string, string, MappingState, DateTime>
                                                                                                   (
                                    c.Item1,
                                    c.Item2,
                                    c.Item3,
                                    b.Value.ToString(),
                                    (MappingState)b.Mapping,
                                    new DateTime(b.Timestamp)
                                                                                                   );
                                result.Add(t);
                            }
                        }
                    }
                }
            }
            catch (ArgumentException argumentException)
            {
                throw argumentException;
            }
            catch (Exception e)
            {
                #region logging
                //logging exception
                var messageEx = new StringBuilder();
                messageEx.Append("ValueManager_GetData: Can't create List of PluginDatas" + ". " + e.ToString());
                MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);

                //TODO remove this log
                Logger.Instance.WriteEntry("ValueManager_GetData: error. " + e.StackTrace, LogType.Debug);
                #endregion
                return(null);
            }

            //TODO remove this log
            Logger.Instance.WriteEntry("ValueManager_GetData: Data createtd and returned: " + result.Count + " for " + macAndProperties.First().Item1 + macAndProperties.First().Item2, LogType.Debug);

            return(result);
        }
Example #29
0
        /// <summary>
        /// Gets the complete data for serveral plugins of certain workstations and a certain timespan.
        /// </summary>
        /// <param name="macAndProperties"> A list containing tuples of:  MAC | PluginName | IndicatorName | LowerBound? | UpperBound? | Maximum numer of results?</param>
        /// <returns>A list containing tuples of: MAC | PluginName | IndicatorName | Value | Mapping | Time</returns>
        public List <Tuple <string, string, string, string, MappingState, DateTime> > GetDataOLDAPPROACH(List <Tuple <string, string, string, DateTime?, DateTime?, int?> > macAndProperties)
        {
            #region check arguments
            if (macAndProperties == null || macAndProperties.Count == 0)
            {
                throw new ArgumentException("macAndProperties list item false.", "macAndProperties");
            }
            #endregion

            List <Tuple <string, string, string, string, MappingState, DateTime> > result = new List <Tuple <string, string, string, string, MappingState, DateTime> >();


            using (var dataContext = DataContextFactory.CreateReadOnlyDataContext())
            {
                //current:  (MAC | PluginName | IndicatorName | LowerBound? | UpperBound? | Maximum numer of results?)
                foreach (var c in macAndProperties)
                {
                    try
                    {
                        // TODO Arno entfernen
                        //break;

                        #region check arguments
                        if (c.Item1 == null || c.Item1 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "macAdress (Item1)");
                        }
                        if (c.Item2 == null || c.Item2 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "pluginName (Item2)");
                        }
                        if (c.Item3 == null || c.Item3 == "")
                        {
                            throw new ArgumentException("macAndProperties list item false.", "IndicatorName (Item3)");
                        }

                        #endregion

                        //update mapping state
                        UpdateMappingState(c.Item1);

                        //set numbers of values
                        int  numbersOfValues = (c.Item6 != null && c.Item6 > 0) ? (int)c.Item6 : int.MaxValue;
                        long lowerTicks      = (c.Item4 != null) ? c.Item4.Value.Ticks : 0;
                        long upperTicks      = (c.Item5 != null) ? c.Item5.Value.Ticks : long.MaxValue;

                        #region caching for single results, continuing in loop
                        if (numbersOfValues == 1)
                        {
                            Tuple <string, string, string, string, MappingState, DateTime> value = GetCachedIndicator(c.Item1, c.Item2, c.Item3);
                            if (value != null)
                            {
                                result.Add(value);
                                continue;
                            }
                        }
                        #endregion

                        //get valueX type
                        var type = (from q in dataContext.Indicator
                                    where q.Name == c.Item3
                                    select q.ValueType).FirstOrDefault();

                        if (!(type == (byte)Core.DataType.Byte || type == (byte)Core.DataType.Float || type == (byte)Core.DataType.Int || type == (byte)Core.DataType.String))
                        {
                            continue;
                        }

                        //get valueX, create sub-results and add them to the result
                        #region byte
                        if (type == (byte)Core.DataType.Byte)
                        {
                            var byteResult = PrecompiledQueries.GetByteValues(dataContext, c.Item1, c.Item2, c.Item3, lowerTicks, upperTicks, numbersOfValues);
                            result.AddRange(byteResult);
                        }
                        #endregion

                        #region int
                        if (type == (byte)DataType.Int)
                        {
                            var intResult = PrecompiledQueries.GetIntValues(dataContext, c.Item1, c.Item2, c.Item3, lowerTicks, upperTicks, numbersOfValues);
                            result.AddRange(intResult);
                        }
                        #endregion

                        #region float
                        if (type == (byte)DataType.Float)
                        {
                            var floatResult = PrecompiledQueries.GetFloatValues(dataContext, c.Item1, c.Item2, c.Item3, lowerTicks, upperTicks, numbersOfValues);
                            result.AddRange(floatResult);
                        }
                        #endregion

                        #region string
                        if (type == (byte)DataType.String)
                        {
                            var stringResult = PrecompiledQueries.GetStringValues(dataContext, c.Item1, c.Item2, c.Item3, lowerTicks, upperTicks, numbersOfValues);
                            result.AddRange(stringResult);
                        }
                        #endregion

                        //cache first element
                        if (numbersOfValues == 1 && result.ElementAt(0) != null)
                        {
                            this.CacheIndicator(result.ElementAt(0));
                        }
                    }
                    catch (Exception e)
                    {
                        #region logging
                        //logging exception
                        var messageEx = new StringBuilder();
                        messageEx.Append("ValueManager_GetData: Can't create List of PluginDatas" + ". " + e.ToString() + " StackTrace: " + e.StackTrace);
                        MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);
                        #endregion
                    }
                }
            }

            //TODO remove this log
            Logger.Instance.WriteEntry("ValueManager_GetData: Data createtd and returned: " + result.Count + " elements for " + macAndProperties.Count() + " mac/plugin/indicator combis starting with " + macAndProperties.First().Item1 + " and Plugin " + macAndProperties.First().Item2, LogType.Debug);

            return(result);
        }
Example #30
0
        /// <summary>
        /// Initializes a cluster manager and starts the acquisition for all nodes.
        /// </summary>
        /// <param name="url">The url of the head-node.</param>
        /// <param name="username">The username to login.</param>
        /// <param name="password">The password to login.</param>
        /// <param name="platform">The platform of the cluster.</param>
        /// <param name="id">An ID for the cluster, to be able to have multiple clusters of one platform.</param>
        public void Initialize(object cred)
        {
            try
            {
                var credentials = (ClusterCredential)cred;

                timerJobs   = new List <TimerJobBase>();
                clusterType = (Platform)credentials.Platform;
                ID          = credentials.ID;

                if (!OUManager.Instance.Exists(clusterType.ToString() + ID))
                {
                    OUManager.Instance.CreateOU(clusterType.ToString() + ID, null, DateTime.Now);
                }
                using (var datacontext = DataContextFactory.CreateReadOnlyDataContext())
                {
                    var OU = (from p in datacontext.OrganizationalUnit
                              where p.FQDN.Equals(clusterType.ToString() + ID)
                              select p).First();
                    this.OUID = OU.ID;
                }

                switch (clusterType)
                {
                case Platform.Bright:
                    clusterConnection = new BrightClusterConnection();
                    clusterConnection.Init(credentials.HeadNodeUrl, credentials.Username, credentials.Password);
                    clusterNodes = clusterConnection.GetNodes();

                    if (PluginManager.Instance.BrightPlugins != null)
                    {
                        clusterPlugins = PluginManager.Instance.BrightPlugins.ToList();
                        this.AddNodes(clusterNodes);
                    }
                    break;

                case Platform.HPC:
                    clusterConnection = new HpcClusterConnection();
                    clusterConnection.Init(credentials.HeadNodeUrl, credentials.Username, credentials.Password);
                    clusterNodes = clusterConnection.GetNodes();
                    if (PluginManager.Instance.HPCPlugins != null)
                    {
                        clusterPlugins = PluginManager.Instance.HPCPlugins.ToList();
                        this.AddNodes(clusterNodes);
                    }
                    break;

                default:
                    // logging unsupported platform
                    var messageEx = new StringBuilder();
                    messageEx.Append("ClusterManager_AddNodes: ");
                    messageEx.Append("The platform " + clusterType.ToString());
                    messageEx.Append(" is not supported.");
                    MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception);
                    break;
                }

                // Register this cluster at the metacluster manager
                MetaClusterManager.Instance.AddCluster(this);
            }
            catch (Exception e)
            {
                Logger.Instance.WriteEntry("ClusterManager_Initialize: Problem initilizing cluster, " + e.ToString(), LogType.Exception);
            }
        }