private void validateSettings()
        {
            //Validate settings and pre-select listbox items

            //Test login
            demoClient = new Icinga2Client(
                txt_url.Text,
                txt_username.Text,
                txt_password.Text,
                (track_timer.Value * 1000 * 60)
                );

            //Retrieve hostgroups
            try
            {
                List <apiDataset> hostgroups = demoClient.getInventory("HostGroup");
                foreach (apiDataset entry in hostgroups)
                {
                    //add entry
                    lbox_hostgroups.Items.Add(entry.name + " (" + entry.attrs.display_name + ")");
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Unable to connect to Icinga2 instance", Properties.Settings.Default.log_level);
            }
            catch (FormatException)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Unable to connect to Icinga2 instance", Properties.Settings.Default.log_level);
            }
        }
        private void track_timer_Scroll(object sender, EventArgs e)
        {
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Timer is '{0}'", track_timer.Value), Properties.Settings.Default.log_level, 2);

            //Set label
            lbl_track_timer.Text = string.Format("{0} {1}", track_timer.Value, rm.GetString("lbl_minutes"));
        }
 private void update(object sender, EventArgs e)
 {
     //Update data thread
     try
     {
         SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Thread state is: '{0}'", dataThread.ThreadState), Properties.Settings.Default.log_level, 2);
         if (dataThread.ThreadState == ThreadState.WaitSleepJoin || dataThread.ThreadState == ThreadState.Running)
         {
             //already running
             MessageBox.Show(rm.GetString("msgbox_update_running"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         else if (dataThread.ThreadState == ThreadState.Stopped)
         {
             //Start over
             dataThread = new Thread(workerObject.updateData);
             dataThread.Start();
         }
         else
         {
             dataThread.Start();
         }
     }
     catch (ThreadStateException exc)
     {
         SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Error with thread handling: '{0}'", exc.Message), Properties.Settings.Default.log_level, 2);
     }
 }
 private void WorkerObject_complete(Dictionary <string, int> hosts, Dictionary <string, List <string> > services)
 {
     SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Data update retrieved by UI class", Properties.Settings.Default.log_level, 2);
     trayIcon.Icon = Properties.Resources.icinga;
     //Set data and alert failures
     failHosts    = hosts;
     failServices = services;
     updateTime();
     alertInventory();
 }
Beispiel #5
0
        public Icinga2Client(string url, string username, string password, int interval)
        {
            //Set Icinga2 API client information
            setUrl(url);
            setUsername(username);
            setPassword(password);
            setInterval(interval);

            //Set timer
            updateTimer = new System.Threading.Timer(updateData, null, interval, interval);
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Yes, this is Icinga2Client: URL='{0}', username='******', interval='{2}'", getUrl(), getUsername(), getInterval()), Properties.Settings.Default.log_level, 2);

            //INVENTORY TEST
            //getInventory("HostGroup");
            //getInventory("Host", "", new string[] { "name", "display_name", "state", "acknowledgement" });
        }
 private void box_logmode_SelectedIndexChanged(object sender, EventArgs e)
 {
     //Log mode
     if (box_logmode.SelectedItem.ToString() == rm.GetString("logger_eventlog"))
     {
         loggerMode = "eventlog";
     }
     else if (box_logmode.SelectedItem.ToString() == rm.GetString("logger_file"))
     {
         loggerMode = "file";
     }
     else
     {
         loggerMode = "console";
     }
     SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, String.Format("Log mode changed to '{0}'", loggerMode), Properties.Settings.Default.log_level, 2);
 }
 private void box_loglevel_SelectedIndexChanged(object sender, EventArgs e)
 {
     //Log level
     if (box_loglevel.SelectedItem.ToString() == rm.GetString("logger_debug"))
     {
         loggerLevel = 2;
     }
     else if (box_loglevel.SelectedItem.ToString() == rm.GetString("logger_info"))
     {
         loggerLevel = 1;
     }
     else
     {
         loggerLevel = 0;
     }
     SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Log level changed to '{0}'", loggerLevel), Properties.Settings.Default.log_level, 2);
 }
 private void box_sound_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         //Play sound
         var controller = new Busylight.SDK();
         controller.Alert(new Busylight.BusylightColor {
             RedRgbValue = 0, GreenRgbValue = 0, BlueRgbValue = 0
         },
                          dictSound[box_sound.SelectedItem.ToString()],
                          dictVol[track_volume.Value]);
         Thread.Sleep(3000);
         controller.Terminate();
     }
     catch (KeyNotFoundException)
     {
         SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Something went wrong when defining the sound based on the form's current selection", Properties.Settings.Default.log_level, 2);
     }
 }
        private void track_volume_Scroll(object sender, EventArgs e)
        {
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Value is '{0}', setting will be '{1}'", track_volume.Value, dictVol[track_volume.Value].ToString()), Properties.Settings.Default.log_level, 2);

            try
            {
                //Demonstrate
                var controller = new Busylight.SDK();
                controller.Alert(new Busylight.BusylightColor {
                    RedRgbValue = 0, GreenRgbValue = 0, BlueRgbValue = 0
                }, dictSound[box_sound.SelectedItem.ToString()],
                                 dictVol[track_volume.Value]
                                 );

                //Set label
                lbl_track_volume.Text = dictVol[track_volume.Value].ToString();
            }
            catch (KeyNotFoundException)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Something went wrong when defining the volume based on the form's current selection", Properties.Settings.Default.log_level, 2);
            }
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                //Validate settings
                validateSettings();

                //Save settings
                saveSettings();
                Close();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Unable to connect to Icinga2 instance", Properties.Settings.Default.log_level);
            }
            catch (FormatException)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Unable to connect to Icinga2 instance", Properties.Settings.Default.log_level);
            }
        }
        private void FormSettings_Load(object sender, EventArgs e)
        {
            try
            {
                //Pre-select Icinga settings
                txt_url.Text         = Properties.Settings.Default.icinga_url;
                txt_username.Text    = Properties.Settings.Default.icinga_user;
                txt_password.Text    = Properties.Settings.Default.icinga_pass;
                track_timer.Value    = Properties.Settings.Default.icinga_update_interval;
                lbl_track_timer.Text = string.Format("{0} {1}", track_timer.Value, rm.GetString("lbl_minutes"));
                chkHosts.Checked     = Properties.Settings.Default.icinga_check_hosts;
                chkServices.Checked  = Properties.Settings.Default.icinga_check_services;
                txt_soundfile.Text   = Properties.Settings.Default.sound_file;

                //Pre-select color items
                btn_up_ok.BackColor        = Properties.Settings.Default.color_up_ok;
                btn_unreach_warn.BackColor = Properties.Settings.Default.color_unreach_warn;
                btn_down_crit.BackColor    = Properties.Settings.Default.color_down_crit;
                btn_unknown.BackColor      = Properties.Settings.Default.color_unknown;
                cdg_up_ok.Color            = Properties.Settings.Default.color_up_ok;
                cdg_unreach_warn.Color     = Properties.Settings.Default.color_unreach_warn;
                cdg_down_crit.Color        = Properties.Settings.Default.color_down_crit;
                cdg_unknown.Color          = Properties.Settings.Default.color_unknown;

                //Pre-select sound items
                box_sound.SelectedItem = Properties.Settings.Default.sound.ToString();
                track_volume.Value     = dictVol.FirstOrDefault(x => x.Value == Properties.Settings.Default.sound_volume).Key;
                lbl_track_volume.Text  = dictVol[track_volume.Value].ToString();

                //Pre-select other
                txt_SpamThreshold.Text          = Properties.Settings.Default.spam_thres.ToString();
                chkEnableTips.Checked           = Properties.Settings.Default.balloon_enable;
                chkEnableLyncWorkaround.Checked = Properties.Settings.Default.lync_enable;
                chkEnableTipStart.Checked       = Properties.Settings.Default.balloon_enable_start;

                //Add logger entries
                box_logmode.Items.Add(rm.GetString("logger_console"));
                box_logmode.Items.Add(rm.GetString("logger_file"));
                box_logmode.Items.Add(rm.GetString("logger_eventlog"));
                box_loglevel.Items.Add(rm.GetString("logger_error"));
                box_loglevel.Items.Add(rm.GetString("logger_info"));
                box_loglevel.Items.Add(rm.GetString("logger_debug"));

                //Log mode
                switch (Properties.Settings.Default.log_mode)
                {
                case "eventlog":
                    //Eventlog
                    box_logmode.SelectedItem = rm.GetString("logger_eventlog");
                    loggerMode = "eventlog";
                    break;

                case "file":
                    //file
                    box_logmode.SelectedItem = rm.GetString("logger_file");
                    loggerMode = "file";
                    break;

                case "console":
                    //console
                    box_logmode.SelectedItem = rm.GetString("logger_console");
                    loggerMode = "console";
                    break;
                }
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Log mode is '{0}'", loggerMode), Properties.Settings.Default.log_level, 2);

                //Log level
                switch (Properties.Settings.Default.log_level)
                {
                case 0:
                    //Error
                    box_loglevel.SelectedItem = rm.GetString("logger_error");
                    loggerLevel = 0;
                    break;

                case 1:
                    //Info
                    box_loglevel.SelectedItem = rm.GetString("logger_info");
                    loggerLevel = 1;
                    break;

                case 2:
                    //Debug
                    box_loglevel.SelectedItem = rm.GetString("logger_debug");
                    loggerLevel = 2;
                    break;
                }
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Log level is '{0}'", loggerLevel), Properties.Settings.Default.log_level, 2);

                //Validate
                validateSettings();

                //Pre-select listbox items
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Hostgroup filter is '{0}'", Properties.Settings.Default.icinga_hostgroups), Properties.Settings.Default.log_level, 2);
                for (int i = 0; i < lbox_hostgroups.Items.Count; i++)
                {
                    if (Properties.Settings.Default.icinga_hostgroups.Contains(lbox_hostgroups.Items[i].ToString().Substring(0, lbox_hostgroups.Items[i].ToString().IndexOf(" "))))
                    {
                        SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Pre-selecting item '{0}'", lbox_hostgroups.Items[i].ToString()), Properties.Settings.Default.log_level, 2);
                        lbox_hostgroups.SetSelected(i, true);
                    }
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Unable to pre-select settings, might by fscked up or unset", Properties.Settings.Default.log_level, 1);
            }
        }
Beispiel #12
0
        private string getHTMLPostResult(string url, string content)
        {
            //This function is proudly inspired by: http://stackoverflow.com/questions/16642196/get-html-code-from-website-in-c-sharp
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("POST: '{0}' (Content: '{1}')", url, content), Properties.Settings.Default.log_level, 2);

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            try
            {
                //Create request
                HttpWebRequest request = HttpWebRequest.CreateHttp(url);

                //Set headers
                request.Headers["X-HTTP-Method-Override"] = "GET";
                request.Method = WebRequestMethods.Http.Post;

                //Set user-agent and credentials
                //Proudly inspired by: http://stackoverflow.com/questions/4334521/c-sharp-httpwebrequest-using-basic-authentication
                request.UserAgent   = "IcingaBusylightAgent";
                request.Credentials = createCredentials();

                //Set payload and length
                byte[] contentArray = Encoding.UTF8.GetBytes(content);
                request.ContentLength = contentArray.Length;
                request.ContentType   = "application/json";

                //Write to stream
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(contentArray, 0, contentArray.Length);
                dataStream.Close();

                //Get response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Return string if valid result
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //Create stream reader
                    Stream       receiveStream = response.GetResponseStream();
                    StreamReader readStream    = null;

                    //Try to guess character set
                    if (response.CharacterSet == "")
                    {
                        readStream = new StreamReader(receiveStream);
                    }
                    else
                    {
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                    }

                    //Read data and close streams
                    string data = readStream.ReadToEnd();
                    response.Close();
                    readStream.Close();
                    return(data);
                }
                else
                {
                    //Impossibru!
                    return(null);
                }
            }
            catch (System.Net.WebException e)
            {
                //Could not access information
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Could not access information, error: {0}", e.Message), Properties.Settings.Default.log_level);
                return(null);
            }
            catch (System.ArgumentException e)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Error: {0}", e.Message), Properties.Settings.Default.log_level);
                return(null);
            }
            catch (Exception e)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Generic error: {0}", e.Message), Properties.Settings.Default.log_level);
                return(null);
            }
        }
        private void saveSettings()
        {
            //Save _all_ the settings

            //Set Icinga settings
            Properties.Settings.Default.icinga_url             = txt_url.Text;
            Properties.Settings.Default.icinga_user            = txt_username.Text;
            Properties.Settings.Default.icinga_pass            = txt_password.Text;
            Properties.Settings.Default.icinga_update_interval = track_timer.Value;
            Properties.Settings.Default.icinga_check_hosts     = chkHosts.Checked;
            Properties.Settings.Default.icinga_check_services  = chkServices.Checked;

            //Set hostgroup filter
            string new_filter = "";
            string temp       = null;

            if (lbox_hostgroups.SelectedItems.Count > 0)
            {
                for (int i = 0; i < lbox_hostgroups.SelectedItems.Count; i++)
                {
                    temp = lbox_hostgroups.SelectedItems[i].ToString();
                    temp = temp.Substring(0, temp.IndexOf(" "));
                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Adding entry to hostgroup filter: '{0}'", temp), Properties.Settings.Default.log_level, 2);
                    if (new_filter == "")
                    {
                        new_filter = temp;
                    }
                    else
                    {
                        new_filter = string.Format("{0};{1}", new_filter, temp);
                    }
                }
            }
            Properties.Settings.Default.icinga_hostgroups = new_filter;

            //Set colors
            Properties.Settings.Default.color_up_ok            = cdg_up_ok.Color;
            Properties.Settings.Default.color_unreach_warn     = cdg_unreach_warn.Color;
            Properties.Settings.Default.color_down_crit        = cdg_down_crit.Color;
            Properties.Settings.Default.color_unknown          = cdg_unknown.Color;
            Properties.Settings.Default.icinga_update_interval = track_timer.Value;

            //Set sound and volume
            Properties.Settings.Default.sound        = dictJingle[box_sound.SelectedItem.ToString()];
            Properties.Settings.Default.sound_volume = dictVol[track_volume.Value];
            Properties.Settings.Default.sound_file   = txt_soundfile.Text;

            //Logging
            Properties.Settings.Default.log_mode  = loggerMode;
            Properties.Settings.Default.log_level = loggerLevel;
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Log mode is '{0}', log level is '{1}'", loggerMode, loggerLevel), Properties.Settings.Default.log_level, 2);

            //Set other
            Properties.Settings.Default.balloon_enable       = chkEnableTips.Checked;
            Properties.Settings.Default.lync_enable          = chkEnableLyncWorkaround.Checked;
            Properties.Settings.Default.spam_thres           = Convert.ToInt32(txt_SpamThreshold.Text);
            Properties.Settings.Default.balloon_enable_start = chkEnableTipStart.Checked;

            //Save changes
            Properties.Settings.Default.Save();
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Saved settings!", Properties.Settings.Default.log_level, 2);
        }
Beispiel #14
0
 private List <apiDataset> updateHosts()
 {
     //Update host information
     SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Updating host information"), Properties.Settings.Default.log_level, 2);
     return(getInventory("Host", "host.state!=00 && host.acknowledgement==0", new String[] { "name", "state", "acknowledgement" }));
 }
Beispiel #15
0
        public List <apiDataset> getInventory(string type = "Hosts", string filter = "", string[] attributes = null)
        {
            //Set default attributes if none given
            attributes = attributes ?? new string[] { "name", "display_name" };

            //OKAY - THE FOLLOWING LINES ARE UGLY AS HELL

            //Implement hostgroup filter
            string temp_filter;

            if (hostgroups.Count > 0)
            {
                temp_filter = "(";
            }
            else
            {
                temp_filter = "";
            }
            Dictionary <string, string> tempVars = new Dictionary <string, string>();

            //OMG I'M GOING TO PUKE
            for (int i = 0; i < hostgroups.Count; i++)
            {
                if (hostgroups[i].Length > 0)
                {
                    string temp_var = randomString(hostgroups[i].Length);
                    temp_filter = temp_filter + temp_var + " in host.groups";
                    if (i < hostgroups.Count - 1)
                    {
                        temp_filter = temp_filter + " || ";
                    }
                    try
                    {
                        tempVars.Add(temp_var, hostgroups[i]);
                    }
                    catch (ArgumentException e)
                    {
                        Console.WriteLine("Another exception doing ugly string messup: " + e.Message);
                    }
                }
            }
            if (hostgroups.Count > 0)
            {
                temp_filter = temp_filter + ") && ";
            }

            //Get inventory
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Retrieving objects '{0}' with filter '{1}' and attributes '{2}'", type, filter, string.Join(", ", attributes)), Properties.Settings.Default.log_level, 2);
            string result = "";
            string post   = "";

            try
            {
                //Setup URL prefix based on type
                string url_prefix = "";
                switch (type)
                {
                case "Host":
                    url_prefix = "hosts";
                    break;

                case "HostGroup":
                    url_prefix = "hostgroups";
                    break;

                case "Service":
                    url_prefix = "services";
                    break;
                }
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("URL prefix is '{0}'", url_prefix), Properties.Settings.Default.log_level, 2);

                //Get result
                string attrs = "";
                foreach (string attribute in attributes)
                {
                    if (attrs == "")
                    {
                        attrs = string.Format("\"{0}\"", attribute);
                    }
                    else
                    {
                        attrs = string.Format("{0}, \"{1}\"", attrs, attribute);
                    }
                }

                //VERSION WITHOUT FILTER
                //Set POST data

                /*post = "{ \"type\": \"" + type + "\"";
                 * if (filter != "") { post = post + ", \"filter\": \"" + filter + "\""; }
                 * post = post + ", \"attrs\": [ " + attrs + " ] }";*/

                //Set POST data
                post   = "{ \"type\": \"" + type + "\"";
                filter = temp_filter + filter;
                if (filter != "")
                {
                    post = post + ", \"filter\": \"" + filter + "\"";
                }

                //Append vars if defined
                if (tempVars.Count > 0)
                {
                    //THIS IS SO UGLY I WANT TO PUKE
                    string vars = ", \"filter_vars\": {";
                    foreach (string var in tempVars.Keys)
                    {
                        if (var.Equals(tempVars.Keys.Last()))
                        {
                            //last entry
                            vars = vars + "\"" + var + "\": \"" + tempVars[var] + "\"";
                        }
                        else
                        {
                            //entries remaining
                            vars = vars + "\"" + var + "\": \"" + tempVars[var] + "\", ";
                        }
                    }
                    vars = vars + " }";
                    post = post + vars;
                }

                post = post + ", \"attrs\": [ " + attrs + " ] }";

                //Get result
                result = getHTMLPostResult(url + "v1/objects/" + url_prefix, post);
                //BOO: Removing root level as I'm too lame to do this nicer...
                result = result.Substring(11, (result.Length - 12));
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("RESULT: '{0}'", result), Properties.Settings.Default.log_level, 2);
                //Try to deserialize objects
                var datasetList = JsonConvert.DeserializeObject <List <apiDataset> >(result);
                foreach (apiDataset entry in datasetList)
                {
                    //dump result
                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Name: '{0}', Type: '{1}', Display Name: '{2}', State: '{3}', Acknowledgement: '{4}'",
                                                                                               entry.name, entry.type, entry.attrs.display_name, entry.attrs.state, entry.attrs.acknowledgement), Properties.Settings.Default.log_level, 2);
                }
                return(datasetList);
            }
            catch (UriFormatException e)
            {
                //Connection could not be openend - URL invalid/host down?
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Invalid URL ({0}) (Host unreachable?) - error: {1}", url + "v1/objects/hosts", e.Message), Properties.Settings.Default.log_level);
                return(null);
            }
            catch (ArgumentOutOfRangeException e)
            {
                //No hosts
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("No hosts found matching conditions! ('{0}', '{1}')", e.Message, result), Properties.Settings.Default.log_level);
                return(null);
            }
            catch (Exception e)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Generic error: '{0}'", e.Message), Properties.Settings.Default.log_level, 0);
                return(null);
            }
        }
Beispiel #16
0
        private void alertInventory()
        {
            //Scans the inventory and alerts
            if (failHosts.Count + failServices.Count > Properties.Settings.Default.spam_thres)
            {
                //The shit just hit the fan, gross!
                showTip(rm.GetString("balloon_chaos_title"),
                        rm.GetString("balloon_chaos_msg").Replace("X", failHosts.Count.ToString())
                        .Replace("Y", failServices.Count.ToString()),
                        ToolTipIcon.Warning);
            }
            else
            {
                //Hosts
                try
                {
                    foreach (string host in failHosts.Keys)
                    {
                        if (Properties.Settings.Default.balloon_enable == true)
                        {
                            //Show tooltip if enabled
                            showTip(string.Format("Host {0}", dictStatesHost[failHosts[host]].ToUpper()), string.Format("Host '{0}' {1}", host, dictStatesHost[failHosts[host]]), ToolTipIcon.Error);
                        }

                        SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode,
                                               string.Format("Alarm: Host '{0}' is '{1}'", host, dictStatesHost[failHosts[host]]),
                                               Properties.Settings.Default.log_level, 2);

                        annoyUser(dictColorHost[failHosts[host]]);
                    }

                    //Services
                    foreach (string host in failServices.Keys)
                    {
                        //Only report if host not generally down
                        if (failHosts.ContainsKey(host) == false)
                        {
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode,
                                                   string.Format("Host '{0}' not blacklisted!", host),
                                                   Properties.Settings.Default.log_level, 2);

                            //Report service
                            foreach (string service in failServices[host])
                            {
                                try
                                {
                                    //Extract state and service
                                    int    thisState   = Convert.ToInt32(service.Substring(service.IndexOf(';') + 1));
                                    string thisService = service.Substring(service.IndexOf('!') + 1);
                                    thisService = thisService.Substring(0, thisService.IndexOf(';'));

                                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode,
                                                           string.Format("Alarm: '{0}' on '{1}' is '{2}'", thisService, host, dictStates[thisState]),
                                                           Properties.Settings.Default.log_level, 2);

                                    //Show tooltip if enabled
                                    if (Properties.Settings.Default.balloon_enable == true)
                                    {
                                        showTip(string.Format("Service {0}", dictStates[thisState].ToUpper()),
                                                string.Format("Service '{0}' {1} '{2}' {3}", thisService, rm.GetString("state_on"), host, dictStates[thisState]), dictIcons[thisState]);
                                    }

                                    annoyUser(dictColor[thisState]);
                                }
                                catch (FormatException e)
                                {
                                    //Format error
                                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Format error: '{0}'", e.Message), Properties.Settings.Default.log_level, 2);
                                }
                            }
                        }
                        else
                        {
                            //Ignoring host
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Ignoring host '{0}' as it's down", host), Properties.Settings.Default.log_level, 2);
                        }
                    }
                }
                catch (InvalidOperationException e)
                {
                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Invalid operation: '{0}'", e.Message), Properties.Settings.Default.log_level, 2);
                }

                //Reset Lync/SfB state if enabled
                if (Properties.Settings.Default.lync_enable == true)
                {
                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Resetting Lync/SfB state...", Properties.Settings.Default.log_level, 2);
                    try
                    {
                        lyncClient = LyncClient.GetClient();
                        if (lyncClient.State == ClientState.SignedIn)
                        {
                            //Read state
                            ContactAvailability myAvailability = (ContactAvailability)lyncClient.Self.Contact.GetContactInformation(ContactInformationType.Availability);
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Lync/SfB state is '{0}'", myAvailability.ToString()), Properties.Settings.Default.log_level, 2);
                            //Set color
                            var controller = new Busylight.SDK();
                            controller.Light(dictSkypeColor[myAvailability]);
                        }
                    }
                    catch (System.Runtime.InteropServices.MarshalDirectiveException e)
                    {
                        SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Unable to read Lync/SfB state: '{0}'", e.Message), Properties.Settings.Default.log_level, 0);
                    }
                    catch (Exception e)
                    {
                        SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Unable to read Lync/SfB state: '{0}'", e.Message), Properties.Settings.Default.log_level, 0);
                    }
                }
            }
        }
Beispiel #17
0
 private List <apiDataset> updateServices()
 {
     //Update service information
     SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Updating service information", Properties.Settings.Default.log_level, 2);
     return(getInventory("Service", "service.state!=00 && service.acknowledgement==0", new String[] { "name", "state", "acknowledgement" }));
 }
Beispiel #18
0
        public AgentContext()
        {
            //Import state strings
            dictStates.Add(0, rm.GetString("state_0"));
            dictStates.Add(1, rm.GetString("state_1"));
            dictStates.Add(2, rm.GetString("state_2"));
            dictStates.Add(3, rm.GetString("state_3"));
            dictStatesHost.Add(0, rm.GetString("state_0"));
            dictStatesHost.Add(1, rm.GetString("state_2"));
            dictStatesHost.Add(2, rm.GetString("state_2"));
            dictStatesHost.Add(3, rm.GetString("state_2"));

            //Import color settings
            color_up_ok        = Properties.Settings.Default.color_up_ok;
            color_unreach_warn = Properties.Settings.Default.color_unreach_warn;
            color_down_crit    = Properties.Settings.Default.color_down_crit;
            color_unknown      = Properties.Settings.Default.color_unknown;
            dictColor.Add(0, new BusylightColor
            {
                RedRgbValue   = color_up_ok.R,
                GreenRgbValue = color_up_ok.G,
                BlueRgbValue  = color_up_ok.B
            });
            dictColor.Add(1, new BusylightColor
            {
                RedRgbValue   = color_unreach_warn.R,
                GreenRgbValue = color_unreach_warn.G,
                BlueRgbValue  = color_unreach_warn.B
            });
            dictColor.Add(2, new BusylightColor
            {
                RedRgbValue   = color_down_crit.R,
                GreenRgbValue = color_down_crit.G,
                BlueRgbValue  = color_down_crit.B
            });
            dictColor.Add(3, new BusylightColor
            {
                RedRgbValue   = color_unknown.R,
                GreenRgbValue = color_unknown.G,
                BlueRgbValue  = color_unknown.B
            });
            dictColorHost.Add(0, new BusylightColor
            {
                RedRgbValue   = color_up_ok.R,
                GreenRgbValue = color_up_ok.G,
                BlueRgbValue  = color_up_ok.B
            });
            dictColorHost.Add(1, new BusylightColor
            {
                RedRgbValue   = color_down_crit.R,
                GreenRgbValue = color_down_crit.G,
                BlueRgbValue  = color_down_crit.B
            });
            dictColorHost.Add(2, new BusylightColor
            {
                RedRgbValue   = color_down_crit.R,
                GreenRgbValue = color_down_crit.G,
                BlueRgbValue  = color_down_crit.B
            });
            dictColorHost.Add(3, new BusylightColor
            {
                RedRgbValue   = color_down_crit.R,
                GreenRgbValue = color_down_crit.G,
                BlueRgbValue  = color_down_crit.B
            });

            //Import sound settings
            sound      = Properties.Settings.Default.sound;
            volume     = Properties.Settings.Default.sound_volume;
            sound_file = Properties.Settings.Default.sound_file;

            //Initialize tray icon
            trayIcon = new NotifyIcon()
            {
                Icon        = Properties.Resources.icinga,
                ContextMenu = new ContextMenu(
                    new MenuItem[] {
                    new MenuItem(rm.GetString("mnu_configure"), configure),
                    new MenuItem(rm.GetString("mnu_update"), update),
                    new MenuItem("-"),
                    new MenuItem(rm.GetString("mnu_about"), about),
                    new MenuItem(rm.GetString("mnu_exit"), exit)
                }
                    ),
                Visible = true,
                Text    = "Icinga Busylight Agent"
            };

            //Start data thread
            initializeThread();

            //Show tool-tip
            Assembly     assem     = Assembly.GetEntryAssembly();
            AssemblyName assemName = assem.GetName();
            Version      ver       = assemName.Version;

            if (Properties.Settings.Default.balloon_enable_start == true)
            {
                showTip(rm.GetString("welcome_title"),
                        "Icinga Busylight Agent " + ver.ToString() + " " +
                        rm.GetString("welcome_message"), ToolTipIcon.Info);
            }

            //Initialize log
            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Application startup completed at {0}", DateTime.Now.ToString()), Properties.Settings.Default.log_level, 2);
        }
Beispiel #19
0
        public void updateData(object state)
        {
            //Update data
            try
            {
                inProgress();
                failHosts.Clear();
                failServices.Clear();
            }
            catch (NullReferenceException e)
            {
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Null reference: '{0}'", e.Message), Properties.Settings.Default.log_level, 2);
            }

            try
            {
                lock (this)
                {
                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, "Updating data thread...", Properties.Settings.Default.log_level, 2);

                    //Update host information if enabled
                    if (Properties.Settings.Default.icinga_check_hosts == true)
                    {
                        try
                        {
                            //Get host information
                            List <apiDataset> hostData = updateHosts();
                            foreach (apiDataset entry in hostData)
                            {
                                //Unacknowledged alert
                                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Found UNACKNOWLEDGED host failure - Name: '{0}', State: '{1}', Acknowledgement: '{2}'",
                                                                                                           entry.name, entry.attrs.state, entry.attrs.acknowledgement), Properties.Settings.Default.log_level, 1);

                                //Add to list
                                //failHosts.Add(entry.name);
                                failHosts.Add(
                                    entry.name,
                                    Convert.ToInt32(entry.attrs.state)
                                    );
                            }
                        }
                        catch (ArgumentNullException e)
                        {
                            //Empty dataset
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Empty dataset: '{0}' - so, no faults? :-)", e.Message), Properties.Settings.Default.log_level, 2);
                        }
                        catch (NullReferenceException e)
                        {
                            //Empty dataset
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Empty dataset: '{0}' - so, no faults? :-)", e.Message), Properties.Settings.Default.log_level, 2);
                        }
                    }

                    //Update service information if enabled
                    if (Properties.Settings.Default.icinga_check_services == true)
                    {
                        try
                        {
                            //Get service information
                            List <apiDataset> serviceData = updateServices();
                            foreach (apiDataset entry in serviceData)
                            {
                                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Digging trough apiDataset '{0}'", entry.name), Properties.Settings.Default.log_level, 1);

                                //Unacknowledged alert
                                string hostname = entry.name.Substring(0, entry.name.IndexOf('!'));
                                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Found UNACKNOWLEDGED service failure - Hostname: '{0}' - Name: '{1}', Type: '{2}', State: '{3}', Acknowledgement: '{4}', Raw Service: '{5}'",
                                                                                                           hostname, entry.name, entry.type, entry.attrs.state, entry.attrs.acknowledgement, entry.attrs.name), Properties.Settings.Default.log_level, 1);

                                //Add to list
                                if (failServices.ContainsKey(hostname) == false)
                                {
                                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Adding '{0}' to dictionary", hostname), Properties.Settings.Default.log_level, 2);
                                    //Add dict entry if non-existent
                                    failServices.Add(hostname, new List <string>());
                                }
                                else
                                {
                                    SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("'{0}' already exists in dictionary", hostname), Properties.Settings.Default.log_level, 2);
                                }

                                failServices[hostname].Add(entry.name + ";" + entry.attrs.state);
                            }
                        }
                        catch (ArgumentNullException e)
                        {
                            //Empty dataset
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Empty dataset: '{0}' - so, no faults? :-)", e.Message), Properties.Settings.Default.log_level, 2);
                        }
                        catch (NullReferenceException e)
                        {
                            //Empty dataset
                            SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Empty dataset: '{0}' - so, no faults? :-)", e.Message), Properties.Settings.Default.log_level, 2);
                        }
                    }

                    //Return data
                    complete(failHosts, failServices);
                }
            }
            catch (NullReferenceException e)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Unable to connrect to Icinga2 instance: '{0}'", e.Message), Properties.Settings.Default.log_level);
            }
            catch (FormatException e)
            {
                MessageBox.Show(rm.GetString("msgbox_icinga_unavailable"), rm.GetString("msgbox_error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                SimpleLoggerHelper.Log(Properties.Settings.Default.log_mode, string.Format("Unable to connect to Icinga2 instance: '{0}'", e.Message), Properties.Settings.Default.log_level);
            }
        }