示例#1
0
        private static void PublishKeepAlive()
        {
            try
            {
                List <string> m_redactlist = null;
                var           keepAlive    = m_configsettings["client"];

                keepAlive["timestamp"] = SensuClientHelper.CreateTimeStamp();
                keepAlive["version"]   = m_version_string;
                keepAlive["plugins"]   = "";

                m_redactlist = SensuClientHelper.GetRedactlist((JObject)keepAlive);

                var payload = SensuClientHelper.RedactSensitiveInformaton(keepAlive, m_redactlist);

                Log.Debug("Publishing keepalive");

                var properties = new BasicProperties
                {
                    ContentType  = "application/octet-stream",
                    Priority     = 0,
                    DeliveryMode = 1
                };

                lock (m_lock_pulish)
                {
                    RabbitMQChannel.BasicPublish("", "keepalives", properties, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to publish KeepAlive!");
            }
        }
示例#2
0
        private static void Subscribe(CancellationToken m_tokenl)
        {
            EventingBasicConsumer m_rabbit_consumer = null;

            if (!RabbitMQChannel.IsOpen)
            {
                throw new Exception("RabbitMQ Channel not open!");
            }

            try
            {
                var m_my_queue = RabbitMQChannel.QueueDeclare(SensuClientHelper.CreateQueueName(), false, false, true, null);

                foreach (var subscription in m_configsettings["client"]["subscriptions"])
                {
                    Log.Debug("Declaring Exchange...");
                    RabbitMQChannel.ExchangeDeclare(subscription.ToString(), "fanout", false, false, null);
                    Log.Debug("Done");

                    Log.Info("Binding queue {0} to exchange {1}", m_my_queue.QueueName, subscription);
                    RabbitMQChannel.QueueBind(m_my_queue.QueueName, subscription.ToString(), "");
                    m_rabbit_consumer = new EventingBasicConsumer(RabbitMQChannel);

                    m_rabbit_consumer.Received          += SubscriptionReceived;
                    m_rabbit_consumer.Shutdown          += SubscriptionShutdown;
                    m_rabbit_consumer.ConsumerCancelled += SubscriptionCancelled;

                    RabbitMQChannel.BasicConsume(m_my_queue.QueueName, true, m_rabbit_consumer);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
            }
        }
示例#3
0
        private static void SubscriptionReceived(object sender, BasicDeliverEventArgs e)
        {
            string  m_payload = String.Empty;
            JObject m_check;

            try
            {
                Log.Debug("Received check request");


                if (e.Body != null)
                {
                    m_payload = Encoding.UTF8.GetString(e.Body);

                    if (!SensuClientHelper.TryParseData(m_payload, out m_check))
                    {
                        throw new JsonReaderException();
                    }

                    Log.Debug("Payload Data: {0}", JsonConvert.SerializeObject(m_check, SerializerSettings));

                    Task.Factory.StartNew(() => ProcessCheck(m_check));

                    Log.Debug("Process Check fired!");
                }
                else
                {
                    throw new Exception("payload empty or null");
                }
            }

            catch (JsonReaderException json_r_ex)
            {
                Log.Error(json_r_ex, "Malformed Check request: {0}", m_payload);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "failed to process check request!");
            }
        }
示例#4
0
        public static void ExecuteCheckCommand(JObject check)
        {
            string m_command      = String.Empty;
            string m_checkcommand = String.Empty;
            string m_checkargs    = String.Empty;

            bool      m_skip_publish    = false;
            string    m_tokenparseerror = string.Empty;
            Stopwatch m_stopwatch       = new Stopwatch();
            TimeSpan  m_check_timeout   = TimeSpan.MinValue;

            Log.Debug("Attempting to execute check command {0}", JsonConvert.SerializeObject(check, SerializerSettings));

            try
            {
                if (check["name"] == null)
                {
                    throw new EmptyCheckNameException();
                }

                lock (m_lock_checkinprogress)
                {
                    if (ChecksInProgress.Contains(check["name"].ToString()))
                    {
                        throw new CheckInProgressException();
                    }
                    else
                    {
                        ChecksInProgress.Add(check["name"].ToString());
                    }
                }

                #region "split command and arguments and get check properties"

                m_command = SensuClientHelper.SubstitueCommandTokens(check, out m_tokenparseerror, (JObject)m_configsettings["client"]);
                m_command = m_command.Trim();

                if (check["timeout"] != null)
                {
                    m_check_timeout = TimeSpan.FromSeconds(Double.Parse(check["timeout"].ToString()));
                    Log.Debug("Received a timeout of {0} ms for this Check", m_check_timeout.TotalMilliseconds);
                }

                if (String.IsNullOrWhiteSpace(m_tokenparseerror))
                {
                    if (m_command.Contains(" "))
                    {
                        m_checkcommand = m_command.Split(" ".ToCharArray(), 2)[0];
                        m_checkargs    = m_command.Split(" ".ToCharArray(), 2)[1];
                    }
                    else
                    {
                        m_checkcommand = m_command;
                    }
                }
                else
                {
                    throw new UnmatchedCommandTokensException();
                }

                Log.Info("Formatted Command => {0}", m_command);

                #endregion

                #region "Plugin based check"

                if (m_program_base.Plugins.Count() != 0 && m_checkcommand.StartsWith("!"))
                {
                    Task <ExecuteResult>    m_check_task = null;
                    CancellationTokenSource m_check_cancelationtokensrc = null;
                    CancellationToken       m_check_cancelationtoken;
                    ExecuteResult           m_plugin_return = null;

                    Log.Debug("Checking inf any plugin has register a handler for command {0}", m_checkcommand);

                    foreach (ISensuClientPlugin m_plugin in m_program_base.Plugins)
                    {
                        if (m_plugin.Handlers().Any(handler => handler.ToLower().Equals(m_checkcommand.ToLower())))
                        {
                            Log.Debug("Plugin {0} provides a handler for command {1}", m_plugin.Name(), m_checkcommand);

                            try
                            {
                                m_check_cancelationtokensrc = new CancellationTokenSource();
                                m_plugin_return             = new ExecuteResult();
                                m_stopwatch.Reset();

                                Log.Debug("Passing Command to plugin {0}", m_plugin.Name());

                                Arguments m_command_args = new Arguments(Arguments.SplitCommandLine(m_checkargs));

                                Log.Debug("Parsed Args:");

                                foreach (var arg in m_command_args.ParsedArguments)
                                {
                                    foreach (var value in arg.Value)
                                    {
                                        Log.Debug("{0} => {1}", arg.Key, value.ToString());
                                    }
                                }

                                m_stopwatch.Start();

                                m_check_cancelationtoken = m_check_cancelationtokensrc.Token;

                                m_check_task = Task <ExecuteResult> .Factory.StartNew(() => m_plugin.execute(m_checkcommand, m_command_args), m_check_cancelationtoken);

                                if (!m_check_timeout.Equals(TimeSpan.MinValue))
                                {
                                    m_check_task.Wait((int)m_check_timeout.TotalMilliseconds, m_check_cancelationtoken);
                                }
                                else
                                {
                                    m_check_task.Wait();
                                }

                                if (!m_check_task.IsCompleted | m_check_task.IsCanceled)
                                {
                                    throw new Exception("Check did not completed within the configured timeout!");
                                }

                                m_plugin_return = m_check_task.Result;

                                Log.Debug("Plugin Return: {0} / ExitCode: {1}", m_plugin_return.Output, m_plugin_return.ExitCode);

                                check["output"] = string.Format("{0}", m_plugin_return.Output);
                                check["status"] = m_plugin_return.ExitCode;
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex, ex.Message);

                                check["output"] = "Unexpected error";
                                check["status"] = 2;

                                //Print error of innerexception cause we using Tasks
                                if (ex.InnerException != null)
                                {
                                    Log.Error(ex, ex.InnerException.Message);
                                    throw new UnexpectedCheckException(ex.InnerException.Message);
                                }
                                else
                                {
                                    throw new UnexpectedCheckException(ex.Message);
                                }
                            }
                            finally
                            {
                                m_stopwatch.Stop();

                                check["executed"] = SensuClientHelper.CreateTimeStamp();
                                check["duration"] = string.Format("{0:f3}", ((float)m_stopwatch.ElapsedMilliseconds) / 1000);

                                if (m_check_task != null)
                                {
                                    m_check_task.Dispose();
                                    m_check_cancelationtokensrc.Dispose();
                                }
                            }
                        }
                    }
                }
                #endregion

                else
                {
                    #region "Normal 'legacy' Check"

                    Process m_check_process = null;

                    ProcessStartInfo m_process_start_info = new ProcessStartInfo(Environment.ExpandEnvironmentVariables(m_checkcommand))
                    {
                        WindowStyle            = ProcessWindowStyle.Hidden,
                        UseShellExecute        = false,
                        RedirectStandardError  = true,
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        Arguments = Environment.ExpandEnvironmentVariables(m_checkargs)
                    };

                    try
                    {
                        m_check_process = new Process {
                            StartInfo = m_process_start_info
                        };

                        m_check_process.Start();
                        m_stopwatch.Start();

                        if (!m_check_timeout.Equals(TimeSpan.MinValue))
                        {
                            bool wait_result = m_check_process.WaitForExit((int)m_check_timeout.TotalMilliseconds);

                            if (!wait_result)
                            {
                                m_check_process.Kill();
                            }
                        }
                        else
                        {
                            m_check_process.WaitForExit();
                        }

                        check["output"] = string.Format("{0}{1}", m_check_process.StandardOutput.ReadToEnd(), m_check_process.StandardError.ReadToEnd());
                        check["status"] = m_check_process.ExitCode;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, ex.Message);

                        check["output"] = "Unexpected error";
                        check["status"] = 2;
                    }
                    finally
                    {
                        m_stopwatch.Stop();

                        check["executed"] = SensuClientHelper.CreateTimeStamp();
                        check["duration"] = string.Format("{0:f3}", ((float)m_stopwatch.ElapsedMilliseconds) / 1000);

                        if (m_check_process != null)
                        {
                            m_check_process.Dispose();
                        }
                    }

                    #endregion
                }
            }

            catch (CheckInProgressException)
            {
                m_skip_publish = true;
                Log.Warn("Previous check command execution in progress {0}", check["command"]);
            }

            catch (EmptyCheckNameException)
            {
                check["output"] = "Check didn't have a valid name";
                check["status"] = 3;
                check["handle"] = false;
            }

            catch (UnexpectedCheckException ex)
            {
                check["output"] = string.Format("Unexpected error: {0}", ex.Message);
                check["status"] = 2;
            }

            catch (UnmatchedCommandTokensException)
            {
                check["output"] = string.Format("Unmatched command tokens: {0}", m_tokenparseerror);
                check["status"] = 3;
                check["handle"] = false;
            }

            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
                check["output"] = "Unkndown error!";
                check["status"] = 2;
            }

            finally
            {
                if (!m_skip_publish)
                {
                    PublishResult(check);
                }
                else
                {
                    Log.Debug("Skipped Check Result publish - trying to rmeove from 'CheckInProgressList'");

                    lock (m_lock_checkinprogress)
                    {
                        if (ChecksInProgress.Contains(check["name"].ToString()))
                        {
                            ChecksInProgress.Remove(check["name"].ToString());
                        }
                    }
                }
            }
        }